如何正确处理 ASP.NET MVC 中控制器抛出的异常?这HandleError
属性似乎只处理 MVC 基础结构引发的异常,而不处理我自己的代码引发的异常。
使用这个 web.config
<customErrors mode="On">
<error statusCode="401" redirect="/Errors/Http401" />
</customErrors>
用下面的代码
namespace MvcApplication1.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
// Force a 401 exception for testing
throw new HttpException(401, "Unauthorized");
}
}
}
没有达到我所希望的结果。相反,我收到通用 ASP.NET 错误页面,告诉我修改 web.config 以查看实际的错误信息。但是,如果我返回无效视图而不是抛出异常,则会得到 /Shared/Views/Error.aspx 页面:
return View("DoesNotExist");
像我上面所做的那样在控制器中抛出异常似乎绕过了所有HandleError
那么创建错误页面的正确方法是什么以及如何很好地使用 MVC 基础设施呢?
Controller.OnException(ExceptionContext context)
。覆盖它。
protected override void OnException(ExceptionContext filterContext)
{
// Bail if we can't do anything; app will crash.
if (filterContext == null)
return;
// since we're handling this, log to elmah
var ex = filterContext.Exception ?? new Exception("No further information exists.");
LogException(ex);
filterContext.ExceptionHandled = true;
var data = new ErrorPresentation
{
ErrorMessage = HttpUtility.HtmlEncode(ex.Message),
TheException = ex,
ShowMessage = !(filterContext.Exception == null),
ShowLink = false
};
filterContext.Result = View("ErrorPage", data);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)