Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a view for HttpNotFound() in ASP.Net MVC 3?

Is there a way to return the same view every time a HttpNotFoundResult is returned from a controller? How do you specify this view? I'm guessing configuring a 404 page in the web.config might work, but I wanted to know if there was a better way to handle this result.

Edit / Follow up:

I ended up using the solution found in the second answer to this question with some slight tweaks for ASP.Net MVC 3 to handle my 404s: How can I properly handle 404s in ASP.Net MVC?

like image 593
Dave Brace Avatar asked Feb 13 '11 17:02

Dave Brace


People also ask

What does return View () in MVC do?

This process determines which view file is used based on the view name. The default behavior of the View method ( return View(); ) is to return a view with the same name as the action method from which it's called.

How do I return a view in asp net?

To return a view from the controller action method, we can use View() method by passing respective parameters. return View(“ViewName”) – returns the view name specified in the current view folder (view extension name “.

What is HttpNotFound?

HttpNotFoundResult class and HttpNotFound() method are easy ways how to let server and browser know that resource asked by visitor is not found. It is also important information for search engine spiders because they are able to correct their indexes based on that information.

Can I return ActionResult Instead of view results?

When you set Action's return type ActionResult , you can return any subtype of it e.g Json,PartialView,View,RedirectToAction.


1 Answers

HttpNotFoundResult doesn't render a view. It simply sets the status code to 404 and returns an empty result which is useful for things like AJAX but if you want a custom 404 error page you could throw new HttpException(404, "Not found") which will automatically render the configured view in web.config:

<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite">    <error statusCode="404" redirect="/Http404.html" /> </customErrors> 
like image 171
Darin Dimitrov Avatar answered Sep 18 '22 14:09

Darin Dimitrov