0

有人可以解释我如何将自定义404和500错误添加到我的项目?我试图通过将此添加到Web.config中:自定义错误MVC 5

<customErrors mode="On"> 
    <error code="404" path="404.html" /> 
    <error code="500" path="500.html" /> 
</customErrors> 

回答

0

如果控制器的操作方法引发异常,则会调用OnException方法。与HandleErrorAttribute不同,它还会捕获404和其他HTTP错误代码,并且不需要打开customErrors。

它是通过在控制器重写onException的方法来实现:

protected override void OnException(ExceptionContext filterContext) 
{ 
filterContext.ExceptionHandled = true; 

// Redirect on error: 
filterContext.Result = RedirectToAction("Index", "Error"); 

// OR set the result without redirection: 
filterContext.Result = new ViewResult 
{ 
    ViewName = "~/Views/Error/Index.cshtml" 
}; 
} 

随着filterContext.ExceptionHandled属性,您可以检查是否异常已在较早阶段处理(例如HandleErrorAttribute):

if(filterContext.ExceptionHandled) return; 互联网上的许多解决方案都建议创建一个基本控制器类并在一个地方实现OnException方法以获取全局错误处理程序。

但是,这并不理想,因为OnException方法几乎与其范围内的HandleErrorAttribute一样有限。您最终会在至少另一个地方复制您的作品。

0

这是我最近看过的最好的文章,让我们来了解一下你将要进入的乐趣吧http://benfoster.io/blog/aspnet-mvc-custom-error-pages 我的customErrors元素看起来像这样。

<customErrors mode="Off" redirectMode="ResponseRewrite"> 
    <error statusCode="404" redirect="/404.aspx" /> 
    <error statusCode="500" redirect="/500.aspx"/> 
</customErrors>