加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:10:15 所属栏目:百科 来源:网络整理
导读:参见英文答案 Custom Errors works for HttpCode 403 but not 500?2 我试图为MVC网站设置自定义错误.我的404页面工作正常,但是当测试服务器错误时,我得到默认消息: Sorry,an error occurred while processing your request. 而不是我的自定义页面. 我已经在
参见英文答案 > 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错误.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读