Displaying custom error CSHTML page in MVC5 on 404

2019-03-30 21:24发布

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.

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.

What I have in my web.config:

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

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>

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.

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!

1条回答
够拽才男人
2楼-- · 2019-03-30 21:46

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");
    }
}
查看更多
登录 后发表回答