20

How can I Handler 404 errors without the framework throwing an Exception 500 error code?

Peter
2,8223 gold badges35 silver badges45 bronze badges
asked Sep 20, 2008 at 17:31

4 Answers 4

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
87.5k123 gold badges428 silver badges701 bronze badges
answered Sep 20, 2008 at 17:38
Sign up to request clarification or add additional context in comments.

5 Comments

Just an FYI, The above linked post is returning a 404 (oh the irony). The new address is: jason.whitehorn.ws/2008/06/17/…
The 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.
Unfortunatelly the link doesn't work. Even jason.whitehorn.ws is not accessible :|
This is fine for situations where routes don't match, but doesn't help when an id is not valid for example...
@JasonWhitehorn 404 again
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.

answered Sep 21, 2008 at 17:48

1 Comment

Good idea. Check out this solution which incorporates a HandleUnknownAction override: stackoverflow.com/questions/619895/…
4

throw new HttpException(404, "Resource Not Found");

answered May 10, 2010 at 14:33

Comments

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);
}
answered Dec 15, 2011 at 19:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.