I'm building my first ASP.NET MVC website, and I'm trying to figure out how to implement a 404 page.
Should I create a controller called "404Controller?" If so, how do I then register this Controller with IIS so that it redirects 404s to that page? Also, in a situation where something is not found (in the database, for example) by some other Controller code, how would I redirect the request to my 404 page?
You can use the <customErrors> in web. config to display custom pages when exceptions occurred in MVC application with the response status code 200. For SEO reason, you may want to display a custom error page and return an appropriate error code in ASP.NET webform or MVC application.
Best web development and SEO practices dictate that any webpage which does not exist, return an HTTP response code of 404, or Not Found. Basically, this response code means that the URL that you're requesting does not exist.
There's no single answer for what your are trying to do, the simplest and what I like is using the HttpException
class, e.g.
public ActionResult ProductDetails(int id) {
Product p = this.repository.GetProductById(id);
if (p == null) {
throw new HttpException(404, "Not Found");
}
return View(p);
}
On web.config you can configure customError pages, e.g.
<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">
<error statusCode="404" redirect="Views/Errors/Http404.aspx" />
</customErrors>
The favorite option for me is to return a view called 404.
if (article == null)
return View("404");
This will let you the option to have a generic 404 view in the shared folder, and a specific 404 view to the article controller.
In addition, a big plus is that there is no redirect over here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With