Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h1>Requirements for 404</h1> <p>The following are my requirements for a 404 solution and below i show how i implement it:</p> <ul> <li>I want to handle matched routes with bad actions</li> <li>I want to handle matched routes with bad controllers</li> <li>I want to handle un-matched routes (arbitrary urls that my app can't understand) - i don't want these bubbling up to the Global.asax or IIS because then <a href="https://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/620559#comment-2885216">i can't redirect back into my MVC app properly</a></li> <li>I want a way to handle in the same manner as above, custom 404s - like when an ID is submitted for an object that does not exist (maybe deleted)</li> <li>I want all my 404s to return an MVC view (not a static page) to which i can pump more data later if necessary (<a href="http://www.codinghorror.com/blog/2007/03/creating-user-friendly-404-pages.html" rel="noreferrer">good 404 designs</a>) <em>and</em> they <em>must</em> return the HTTP 404 status code</li> </ul> <h1>Solution</h1> <p>I think you should save <code>Application_Error</code> in the Global.asax for higher things, like unhandled exceptions and logging (like <a href="https://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/620559#620559">Shay Jacoby's answer</a> shows) but not 404 handling. This is why my suggestion keeps the 404 stuff out of the Global.asax file.</p> <h2>Step 1: Have a common place for 404-error logic</h2> <p>This is a good idea for maintainability. Use an <a href="https://stackoverflow.com/questions/108813/404-http-error-handler-in-asp-net-mvc-rc-5/108830#108830">ErrorController</a> so that future improvements to your <a href="http://www.codinghorror.com/blog/2007/03/creating-user-friendly-404-pages.html" rel="noreferrer">well designed 404 page</a> can adapt easily. Also, <strong>make sure your response has the 404 code</strong>!</p> <pre><code>public class ErrorController : MyController { #region Http404 public ActionResult Http404(string url) { Response.StatusCode = (int)HttpStatusCode.NotFound; var model = new NotFoundViewModel(); // If the url is relative ('NotFound' route) then replace with Requested path model.RequestedUrl = Request.Url.OriginalString.Contains(url) &amp; Request.Url.OriginalString != url ? Request.Url.OriginalString : url; // Dont get the user stuck in a 'retry loop' by // allowing the Referrer to be the same as the Request model.ReferrerUrl = Request.UrlReferrer != null &amp;&amp; Request.UrlReferrer.OriginalString != model.RequestedUrl ? Request.UrlReferrer.OriginalString : null; // TODO: insert ILogger here return View("NotFound", model); } public class NotFoundViewModel { public string RequestedUrl { get; set; } public string ReferrerUrl { get; set; } } #endregion } </code></pre> <h2>Step 2: Use a base Controller class so you can easily invoke your custom 404 action and wire up <code>HandleUnknownAction</code></h2> <p>404s in ASP.NET MVC need to be caught at a number of places. The first is <code>HandleUnknownAction</code>.</p> <p>The <code>InvokeHttp404</code> method creates a common place for re-routing to the <code>ErrorController</code> and our new <code>Http404</code> action. Think <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="noreferrer">DRY</a>!</p> <pre><code>public abstract class MyController : Controller { #region Http404 handling protected override void HandleUnknownAction(string actionName) { // If controller is ErrorController dont 'nest' exceptions if (this.GetType() != typeof(ErrorController)) this.InvokeHttp404(HttpContext); } public ActionResult InvokeHttp404(HttpContextBase httpContext) { IController errorController = ObjectFactory.GetInstance&lt;ErrorController&gt;(); var errorRoute = new RouteData(); errorRoute.Values.Add("controller", "Error"); errorRoute.Values.Add("action", "Http404"); errorRoute.Values.Add("url", httpContext.Request.Url.OriginalString); errorController.Execute(new RequestContext( httpContext, errorRoute)); return new EmptyResult(); } #endregion } </code></pre> <h2>Step 3: Use Dependency Injection in your Controller Factory and wire up 404 HttpExceptions</h2> <p>Like so (it doesn't have to be StructureMap):</p> <p><em>MVC1.0 example:</em></p> <pre><code>public class StructureMapControllerFactory : DefaultControllerFactory { protected override IController GetControllerInstance(Type controllerType) { try { if (controllerType == null) return base.GetControllerInstance(controllerType); } catch (HttpException ex) { if (ex.GetHttpCode() == (int)HttpStatusCode.NotFound) { IController errorController = ObjectFactory.GetInstance&lt;ErrorController&gt;(); ((ErrorController)errorController).InvokeHttp404(RequestContext.HttpContext); return errorController; } else throw ex; } return ObjectFactory.GetInstance(controllerType) as Controller; } } </code></pre> <p><em>MVC2.0 example:</em></p> <pre><code> protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { try { if (controllerType == null) return base.GetControllerInstance(requestContext, controllerType); } catch (HttpException ex) { if (ex.GetHttpCode() == 404) { IController errorController = ObjectFactory.GetInstance&lt;ErrorController&gt;(); ((ErrorController)errorController).InvokeHttp404(requestContext.HttpContext); return errorController; } else throw ex; } return ObjectFactory.GetInstance(controllerType) as Controller; } </code></pre> <p>I think its better to catch errors closer to where they originate. This is why i prefer the above to the <code>Application_Error</code> handler.</p> <p>This is the second place to catch 404s.</p> <h2>Step 4: Add a NotFound route to Global.asax for urls that fail to be parsed into your app</h2> <p>This route should point to our <code>Http404</code> action. Notice the <code>url</code> param will be a relative url because the routing engine is stripping the domain part here? That is why we have all that conditional url logic in Step 1.</p> <pre><code> routes.MapRoute("NotFound", "{*url}", new { controller = "Error", action = "Http404" }); </code></pre> <p>This is the third and final place to catch 404s in an MVC app that you don't invoke yourself. If you don't catch unmatched routes here then MVC will pass the problem up to ASP.NET (Global.asax) and you don't really want that in this situation.</p> <h2>Step 5: Finally, invoke 404s when your app can't find something</h2> <p>Like when a bad ID is submitted to my Loans controller (derives from <code>MyController</code>):</p> <pre><code> // // GET: /Detail/ID public ActionResult Detail(int ID) { Loan loan = this._svc.GetLoans().WithID(ID); if (loan == null) return this.InvokeHttp404(HttpContext); else return View(loan); } </code></pre> <p>It would be nice if all this could be hooked up in fewer places with less code but i think this solution is more maintainable, more testable and fairly pragmatic. </p> <p>Thanks for the feedback so far. I'd love to get more.</p> <p><strong>NOTE: This has been edited significantly from my original answer but the purpose/requirements are the same - this is why i have not added a new answer</strong></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload