Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 HttpNotFound() and 404 error

I have a controller in which I am processing a part of the url and if it matches some criteria I will return a View but if not I will return a HttpNotFound().

Now I have set up a friendly 404 page which a user will be redirected to if a 404 is thrown so why doesn't the HttpNotFound redirect to this page?

I would expect the 404 to be thrown then the page to be redirected to the error page as set up in the web.config but it just shows the default 404 page. I have checked with other urls that don't exist and these all redirect to the proper error page

like image 743
Pete Avatar asked Mar 21 '14 16:03

Pete


2 Answers

As it turns out you're meant to throw an exception:

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

This seems to handle the 404 and then redirect you to the proper page rather than just the IIS 404 page

like image 88
Pete Avatar answered Sep 22 '22 10:09

Pete


Just taking a guess...

The reason that you are not redirected to the friendly 404 page is because IIS/MVC were able to process the request. Then when processing the request you determine that you needed to return a 404 status code to the client.

Personally, I prefer to return a 404 status code and my PageNotFound view similar to this approach that is used by StackOverflow: https://stackoverflow.com/a/499907/84395

like image 26
Cloud SME Avatar answered Sep 21 '22 10:09

Cloud SME