Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle 404 error in config and code in MVC5?

I have implemented exception handling as mentioned in below link

How to pass error message to error view in MVC 5?

It is working fine. But I have requirement to handle 404 Error.

How can I do that?

if I use below code,

<customErrors mode="On">
  <error statusCode="404" redirect="/Home/Error"></error>
</customErrors>

it works well when any 404 error occurs. But in case any other exception occurs then my error.cshtml call twice and show same exception two times.

like image 780
Gaurav123 Avatar asked Sep 02 '16 06:09

Gaurav123


People also ask

How do you throw a 404 error?

throw new HttpException(404, "File Not Found"); return View(); you will invoke the error handelers but it will not set the Status code. throw new HttpException(404, "File Not Found"); return HttpNotFound();

How do you fix HTTP error 404.0 not found The resource you are looking for has been removed had its name changed or is temporarily unavailable?

To resolve this problem, use one of the following methods: Make sure that the requested resource is at the location that the URL points to. Review the URL that you open in the Web browser. Make sure that no custom filters or modules restrict access to the file that you want to browse.

What is 404 error C#?

But if user passes article ID that doesn't exists the page must return code 404 (Not Found) and show the custom 404 page like in the previous situation.


1 Answers

If you will define defaultRedirect attribute for customErrors then error.cshtml will be rendered only once in your case:

 <customErrors mode="On" defaultRedirect="/Home/Error">
          <error statusCode="404" redirect="/Home/Error"/>
 </customErrors>
like image 200
Ankit Sahrawat Avatar answered Sep 29 '22 18:09

Ankit Sahrawat