How do I catch the http status code of server errors into a generic custom error view in ASP.NET MVC

后端 未结 2 1327
面向向阳花
面向向阳花 2020-12-20 01:28

I am trying to implement a general custom error page in ASP.NET MVC 4. I basically set up an Error Layout, which defines a section for outputting the http status code of the

相关标签:
2条回答
  • 2020-12-20 01:50

    The solution I was looking for (after being in the verge of giving up) is described here.

    Summing up the steps:

    1. Set your web.config to redirect to a controller action for each error you want to handle.
    2. Set TryToSkipCustomErrors property of the Response object to true, in each action defined in 1.
    3. Comment out the line filters.Add(new HandleErrorAttribute()); from your filterConfig.cs file.

    Using this approach I finally succeeded in having a redirect to a custom page for error 500. There seems to be some sort of default skip by IIS for 500, because setting a custom page for error 404 does not require neither steps 2 nor 3.

    So, in the end, for each http status code I want to render a custom page, I create a controller action, set the described properties accordingly, and then redirect to the same view, for all actions - where I display @Response.Status, making it enough a generic solution for me.

    0 讨论(0)
  • 2020-12-20 01:55

    If you're using IIS7+ I'd disable "customerrors" like so:

     <customErrors mode="Off" />
    

    and use httpErrors like so:

    <system.webServer>
     <httpErrors errorMode="DetailedLocalOnly" existingResponse="Replace" defaultPath="/error">
         <remove statusCode="404" />
         <error statusCode="404" path="/error/notfound" responseMode="ExecuteURL" />
     </httpErrors>
    ....
    

    This allows you to get a non-url changing error page displaying with a 404 status code using the following in your controller:

    public class ErrorController : Controller
    {
    public ActionResult notfound()
        {
            Response.TrySkipIisCustomErrors = true;
            Response.StatusCode = (int)HttpStatusCode.NotFound;
            return View("OneErrorViewToRuleThemAll");
        }
    }
    

    ps. "errorMode" needs to change to "Custom" to see it locally....depending on your local setup (i.e. if you're using IISExpress) you might not see the proper error until you upload to a live server.

    pps. you could have the single view "OneErrorViewToRuleThemAll" to handle the on-screen output of whatever status codes you decide to handle this way. Each ErrorController Action would end up on this view.

    0 讨论(0)
提交回复
热议问题