Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IIS showing server error instead of custom errors

I'm using MVC 5 and I'm handling my errors with a custom views for errors such as (404, 403.. etc) It works fine on my local IIS but when I publish on a staging server it shows the IIS server error messages regarding these error codes.

It's showing this message:

Showing this message

instead of:

instead of this

I have modified the 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 in-order to show my custom error messages?

like image 461
SVI Avatar asked Oct 19 '14 05:10

SVI


1 Answers

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

<configuration>
    <system.webServer>
        <httpErrors existingResponse="PassThrough" />
    </system.webServer>
</configuration>
like image 160
Samer Shawish Avatar answered Nov 15 '22 08:11

Samer Shawish