How can I Handler 404 errors without the framework throwing an Exception 500 error code?
Asked
Active
Viewed 1.8k times
4 Answers
21
http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx gives the following explanation:
Add a wildcard routing rule as your final rule:
routes.MapRoute("Error",
"{*url}",
new { controller = "Error", action = "Http404" });
Any request that doesn't match another rule gets routed to the Http404 action of the Error controller, which you also need to configure:
public ActionResult Http404(string url) {
Response.StatusCode = 404;
ViewData["url"] = url;
return View();
}

Pure.Krome
- 84,693
- 113
- 396
- 647

dave
- 989
- 5
- 8
-
16Just an FYI, The above linked post is returning a 404 (oh the irony). The new address is: http://jason.whitehorn.ws/2008/06/17/Friendly-404-Errors-In-ASPNET-MVC.aspx – Jason Whitehorn Nov 25 '08 at 04:21
-
4The only problem here is that so much matches the typical /{controller}/{action}/{id} route. To get around the problem, I explicitly defined all my routes and got rid of it. – BC. Mar 15 '09 at 01:31
-
4Unfortunatelly the link doesn't work. Even http://jason.whitehorn.ws/ is not accessible :| – stej Aug 12 '09 at 06:35
-
This is fine for situations where routes don't match, but doesn't help when an id is not valid for example... – UpTheCreek Feb 04 '11 at 16:11
-
@JasonWhitehorn 404 again – Bryan Denny May 22 '14 at 15:27
9
You can also override HandleUnknownAction within your controller in the cases where a request does match a controller, but doesn't match an action. The default implementation does raise a 404 error.

Haacked
- 58,045
- 14
- 90
- 114
-
Good idea. Check out this solution which incorporates a `HandleUnknownAction` override: http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/2577095#2577095 – Matt Kocaj Apr 05 '10 at 05:57
0
With MVC 3 you can return HttpNotFound() to properly return a 404.
Like this:
public ActionResult Download(string fontName)
{
FontCache.InitalizeFonts();
fontName = HttpUtility.UrlDecode(fontName);
var font = FontCache.GetFontByName(fontName);
if (font == null)
return HttpNotFound();
return View(font);
}

Bryan Legend
- 6,790
- 1
- 59
- 60