Search code examples
c#asp.net-mvcmodel-view-controllerasp.net-mvc-5

A NotFound method is invoked twice due to my settings in Web.config and Global.asax


I have an MVC5 application. In the config file, I have set the following:

    <httpErrors errorMode="Custom" existingResponse="Replace">
      <clear/>
      <error statusCode="400" responseMode="ExecuteURL" path="/Error/BadRequest" />
      <error statusCode="403" responseMode="ExecuteURL" path="/Error/Forbidden" />
      <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFoundFromWebConfig" />
      <error statusCode="500" responseMode="ExecuteURL" path="/Error/Index" />
    </httpErrors>

I also in the Global.asax.cs file in the Application_Error method, handle the error:

     Response.TrySkipIisCustomErrors = true;
     HttpContext.Current?.Response.Redirect("~/Error/NotFound", true);

Now, when I hit a controller for example mysite/contactus/blah, I see that the NotFound method is invoked twice.

I have tried to disable one of these two but I get different issues when I do that. For example if I remove the one in the config file, when 404 happens, I get that ugly black and red page. If I remove the second one, I get redirected to a blank page.

Can someone please help? Thank you.


Solution

  • As per conversation above, I removed the error handling from the Global.asax andI also had a catch all route in my routeconfig file which I removed since I already restrict my routes by a condition. This fixed the issue.