IIS shows server error instead of user errors

I use MVC 5 and I process my errors with custom views for errors like (404, 403, etc.), It works fine on my local IIS, but when published to an intermediate server, it shows IIS server error messages regarding these error codes.

Shows this message:

Showing this message

instead

instead of this

I changed web.config for <customErrors mode="Off" />

Global.asax

  if ((Context.Server.GetLastError() is UnauthorizedAccessException)) { log.LogError(Context.Server.GetLastError().Message, Context.Server.GetLastError()); customErrorPage = @"~/Error/?id=403"; //security } else if ((Context.Server.GetLastError() is HttpException) && (((HttpException)Context.Server.GetLastError()).GetHttpCode() == 404)) { //** Handle 404 error and response code log.LogError("404", Context.Server.GetLastError()); customErrorPage = @"~/Error/?id=404"; } else { log.LogError(Context.Server.GetLastError().Message, Context.Server.GetLastError()); customErrorPage = @"~/Error"; } if (ConfigurationHelper.Common.ShowCustomErrorPage) { var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext); Response.Redirect(urlHelper.Content(customErrorPage), false); Server.ClearError(); } 

Error controller:

  public ActionResult Index(string id) { if (!string.IsNullOrEmpty(id) && id.Equals("404")) { Response.StatusCode = 404; return !Request.IsAjaxRequest() ? (ActionResult)View("404") : PartialView("404"); } if (!string.IsNullOrEmpty(id) && id.ToLower().Equals("403")) { Response.StatusCode = 403; return !Request.IsAjaxRequest() ? (ActionResult)View("Security") : PartialView("Security"); } return !Request.IsAjaxRequest() ? (ActionResult)View("Index") : PartialView("Index"); } 

What should I do to show my custom error messages?

+6
source share
2 answers

Just add the following web.config configuration to go through the IIS default error handling behavior

 <configuration> <system.webServer> <httpErrors existingResponse="PassThrough" /> </system.webServer> </configuration> 
+9
source

Try using

 Response.TrySkipIisCustomErrors = true; 

on your controller. It's better than

 <httpErrors existingResponse="PassThrough" /> 

since PassThrough may lead to some results that you do not always expect. For example, read here how this will make the custom error module return an empty response if the modules do not install any text.

0
source

Source: https://habr.com/ru/post/976930/


All Articles