微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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错误.

原文地址:https://www.jb51.cc/csharp/97767.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐