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

让人想犯罪 __ 提交于 2019-11-29 12:38:28

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!