C# 针对NullReferenceException的RedirectToAction
在获取“对象引用未设置为对象的实例”时,是否有一种使用RedirectToAction的方法。错误C# 针对NullReferenceException的RedirectToAction,c#,asp.net-mvc,C#,Asp.net Mvc,在获取“对象引用未设置为对象的实例”时,是否有一种使用RedirectToAction的方法。错误 我只需要一个提示,而不是一个有效的解决方案。感谢您的帮助。这就是HandleError属性(和功能) 你可以: 在控制器内重写OnException方法 使用HandleError属性(可根据异常类型进行配置) 使用以下两者的小示例: [HandleError(ExceptionType=typeof(NullReferenceException), View="Error")]
我只需要一个提示,而不是一个有效的解决方案。感谢您的帮助。这就是
HandleError
属性(和功能)
你可以:
- 在控制器内重写
方法OnException
- 使用
属性(可根据异常类型进行配置)HandleError
[HandleError(ExceptionType=typeof(NullReferenceException), View="Error")]
public string Home(string name)
{
...
}
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled)
{
return;
}
// do something
base.OnException(filterContext);
}
您可以使用try-catch?@JensKloster,但是异常处理机制有点重。所以更可取的做法是检查对象是否为null,如果为null则重定向。老实说,我认为,生产代码不应该处理
NullReferenceException
,因为它根本不应该被抛出,除非发生了不好的事情。@Leri我同意-我的评论只是一个大脑转储:)我不使用asp.net mvc开发,然而,我用.NET做了很多网络工作,我敢打赌这样处理NullReferenceException
总有一天会成为调试的噩梦。
[HandleError]
public class YourController: Controller
{
[HandleError] // or here
public ActionResult YourAction()
{
// code
return View();
}
}
[HandleError(ExceptionType=typeof(NullReferenceException), View="Error")]
public string Home(string name)
{
...
}
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled)
{
return;
}
// do something
base.OnException(filterContext);
}