繁体   English   中英

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

[英]Displaying custom error CSHTML page in MVC5 on 404 / 500 / any exception?

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

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

我在web.config中有什么:

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

这会导致默认的黄色错误页面。 但是如果我在root中删除error.html页面并使用它:

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

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

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

尝试在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");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM