在404/500 /任何异常的MVC5中显示自定义错误CSHTML页面?

时间:2014-12-12 04:13:19

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor

我一整天都把头发拉了过来。我试图只是在抛出异常时显示一个友好的cshtml页面,因此我的用户体验是一致的 - 我不希望我的用户甚至知道我在UI上的.net堆栈上。

我通过导航到localhost:2922/junkurl进行测试, - 如果网址无法解析,无法找到或以其他方式生成异常,我想显示友好呈现的cshtml页面。

我在web.config中的内容:

<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Views/Shared/Error.cshtml">
</customErrors>

这会产生默认的黄色错误页面。但是如果我在根目录中删除error.html页面并使用它:

<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/error.html">
</customErrors>

有效。唯一的问题是,我不想用直接的html重新构建我的整个Layout / LoginPartial / etc - 我想用razor渲染它。围绕这个的典型方法是什么?如果我错过了答案,我已经做了大量的搜索,所以道歉,我完全不知所措。

如果可能的话,我宁愿从代码中做到这一点,但是根据我的理解,代码只会覆盖一定程度的异常......在某一点上它似乎必须通过配置来处理。我只是希望这是简单的配置!

1 个答案:

答案 0 :(得分:13)

尝试在web.config中使用ErrorController和以下配置

<强>的web.config

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

<强> ErrorController

public class ErrorController : Controller
{
    public ActionResult Index()
    {
        return View("Error");
    }

    public ActionResult NotFound()
    {
        Response.StatusCode = 200;
        return View("NotFound");
    }

    public ActionResult InternalServer()
    {
        Response.StatusCode = 200;
        return View("InternalServer");
    }
}