在404/500/MVC5中显示自定义错误CSHTML页面,出现任何异常? [英] Displaying custom error CSHTML page in MVC5 on 404 / 500 / any exception?

查看:176
本文介绍了在404/500/MVC5中显示自定义错误CSHTML页面,出现任何异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这整天我一直在拔头发.每当出现异常时,我都试图仅显示一个友好的cshtml页面,以使我的UX保持一致-我甚至不希望我的用户从UI知道我在.net堆栈中.

I have been pulling my hair out over this all day. I'm trying to just display a friendly cshtml page whenever an exception is thrown so my UX is consistent - I don't want my users even knowing I'm on the .net stack from the UI, ever.

我正在通过导航到localhost:2922/junkurl进行测试,如果URL无法解析,找不到或生成异常,我想显示一个友好的呈现的cshtml页面.

I'm testing by navigating to localhost:2922/junkurl, - if the URL does not resolve, cannot be found, or otherwise generates an exception, I want to display a friendly rendered cshtml page.

我在web.config中拥有的内容:

What I have in my web.config:

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

这将导致默认的黄色错误页面.但是,如果我在根目录中放置error.html页面并使用它:

This results in the default yellow error page. But if I drop an error.html page in the root and use this:

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

有效.唯一的问题是,我不想直接用html重新构建整个Layout/LoginPartial/etc-我想用剃刀渲染它.解决此问题的典型方法是什么?如果我错过了答案,我已经做了很多关于这种道歉的搜索,我完全茫然了.

It works. The only problem is, I don't want to have to build up my entire Layout / LoginPartial / etc all over again with straight html - I want to render it using razor. What is the typical approach around this? I've done tons of searching on this so apologies if I missed the answer, I'm just completely at a loss.

如果可能的话,我宁愿从代码中执行此操作,但是据我了解,代码将仅涵盖特定级别的异常……在某些时候,似乎必须通过config处理.我只希望它是简单明了的配置!

I would rather do this from code if possible, but I from what I understand, code will only cover a certain level of exceptions... at a certain point it seems it has to be handled via config. I just wish it was straightforward config!

推荐答案

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

Try with an ErrorController and the following config in your web.config

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

这篇关于在404/500/MVC5中显示自定义错误CSHTML页面,出现任何异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆