How to make a catch all route to handle '404 page not found' queries for ASP.NET MVC?

asp.net MvcRoutesHttp Status-Code-404

asp.net Mvc Problem Overview


Is it possible to create a final route that catches all .. and bounces the user to a 404 view in ASP.NET MVC?

NOTE: I don't want to set this up in my IIS settings.

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

Found the answer myself.

[Richard Dingwall][1] has an excellent post going through various strategies. I particularly like the FilterAttribute solution. I'm not a fan of throwing exceptions around willy nilly, so i'll see if i can improve on that :)

For the global.asax, just add this code as your last route to register:

routes.MapRoute(
    "404-PageNotFound",
    "{*url}",
    new { controller = "StaticContent", action = "PageNotFound" }
    );

[1]: http://richarddingwall.name/2008/08/17/strategies-for-resource-based-404-errors-in-aspnet-mvc/ "Click to read Richard's MVC 404 strategies"

Solution 2 - asp.net Mvc

This question came first, but the easier answer came in a later question:

https://stackoverflow.com/questions/553922/custom-asp-net-mvc-404-error-page

> I got my error handling to work by creating an ErrorController that > returns the views in this article. I also had to add the "Catch All" > to the route in global.asax. > > I cannot see how it will get to any of these error pages if it is not > in the Web.config..? My Web.config had to specify: > > customErrors mode="On" defaultRedirect="/Error/Unknown" > > and then I also added: > > error statusCode="404" redirect="/Error/NotFound" > > Hope this helps.

I love this way now because it is so simple:

 <customErrors mode="On" defaultRedirect="~/Error/" redirectMode="ResponseRedirect">
    <error statusCode="404" redirect="~/Error/PageNotFound/" />
 </customErrors>

Solution 3 - asp.net Mvc

Also you can handle NOT FOUND error in Global.asax.cs as below

protected void Application_Error(object sender, EventArgs e)
{
    Exception lastErrorInfo = Server.GetLastError();
    Exception errorInfo = null;

    bool isNotFound = false;
    if (lastErrorInfo != null)
    {
        errorInfo = lastErrorInfo.GetBaseException();
        var error = errorInfo as HttpException;
        if (error != null)
            isNotFound = error.GetHttpCode() == (int)HttpStatusCode.NotFound;
    }
    if (isNotFound)
    {
        Server.ClearError();
        Response.Redirect("~/Error/NotFound");// Do what you need to render in view
    }
}

Solution 4 - asp.net Mvc

Add this lines under your project root web.config File.

 <system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <error statusCode="404" responseMode="ExecuteURL" path="/Test/PageNotFound" />
  <remove statusCode="500" />
  <error statusCode="500" responseMode="ExecuteURL" path="/Test/PageNotFound" />
</httpErrors>
<modules>
  <remove name="FormsAuthentication" />
</modules>

Solution 5 - asp.net Mvc

This might be a problem when you use

throw new HttpException(404);

When you want to catch that, I don't know any other way then editing your web config.

Solution 6 - asp.net Mvc

An alternative to creating a catch-all route is to add an Application_EndRequest method to your MvcApplication per Marco's Better-Than-Unicorns MVC 404 Answer.

Solution 7 - asp.net Mvc

Inside RouterConfig.cs add the follwing piece of code:

  routes.MapRoute(
           name: "Error",
           url: "{id}",
           defaults: new
           {
               controller = "Error",
               action = "PageNotFound"

           });

Solution 8 - asp.net Mvc

If the route cannot be resolved, then MVC framework will through 404 error.. Best approach is to use Exception Filters ... Create a custom exceptionfilter and make like this..

public class RouteNotFoundAttribute : FilterAttribute, IExceptionFilter {
    public void OnException(ExceptionContext filterContext) {
        filterContext.Result  = new RedirectResult("~/Content/RouteNotFound.html");
   }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPure.KromeView Question on Stackoverflow
Solution 1 - asp.net MvcPure.KromeView Answer on Stackoverflow
Solution 2 - asp.net MvcsmdragerView Answer on Stackoverflow
Solution 3 - asp.net MvcMSDsView Answer on Stackoverflow
Solution 4 - asp.net MvcVickyView Answer on Stackoverflow
Solution 5 - asp.net MvcPacoView Answer on Stackoverflow
Solution 6 - asp.net MvcEdward BreyView Answer on Stackoverflow
Solution 7 - asp.net Mvcsolanki devView Answer on Stackoverflow
Solution 8 - asp.net MvcLaxmeesh JoshiView Answer on Stackoverflow