c# – 500内部服务器错误页面在MVC

参见英文答案 > Custom Errors works for HttpCode 403 but not 500?2
我试图为MVC网站设置自定义错误.我的404页面工作正常,但是当测试服务器错误时,我得到认消息:

Sorry,an error occurred while processing your request.

而不是我的自定义页面.

我已经在web.config中设置了这个:

<customErrors mode="On"  defaultRedirect="~/Error/500">
    <error statusCode="404" redirect="~/Error/404" />
    <error statusCode="500" redirect="~/Error/500" />
</customErrors>

我的错误控制器如下:

public class ErrorController : Controller
{
    [ActionName("404")]
    public ActionResult NotFound()
    {
        return View();
    }

    [ActionName("500")]
    public ActionResult ServerError()
    {
        return View();
    }
}

我正在通过在我的一个视图中抛出异常来测试500错误页面

[ActionName("contact-us")]
public ActionResult ContactUs()
{
    throw new DivideByZeroException();
    return View();
}

为什么只处理404错误?如何显示500个错误错误页面

解决方法

想出来了..

创建项目时,Global.asax.cs中留下了一些样板代码

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
   filters.Add(new HandleErrorAttribute());
}

尤其是:

filters.Add(new HandleErrorAttribute());

这将创建一个HandleErrorAttribute的新实例,该实例全局应用于我的所有视图.

没有自定义,如果视图在使用此属性时引发错误,MVC将在共享文件夹中显示认的Error.cshtml文件,其中:“对不起,处理您的请求时出错.来自.

HandleErrorAttribute的文档:

By default,when an action method with the HandleErrorAttribute attribute throws any exception,MVC displays the Error view that is located in the ~/Views/Shared folder.

评论此行解决了问题,并允许我使用自定义错误页面500错误.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...