Correctly send the user to 404 if dynamic content is not found (ASP.NET MVC)

I implemented 404 handling for the general case in ASP.NET MVC 3 since the controller / view was not found. But how should it be processed inside the controller if the user is trying to access what cannot be found? For example, it www.foo.bar/Games/Details/randomjunkwill call this inside GamesController:

public ActionResult Details(string id) // id is 'randomjunk'
{
  if(DoesGameExist(id) == false)
    // Now what?

I could just do it return Redirect('/Errors/Http404');, but that doesn't seem like the right way to do it. Should you throw an exception or something else?

In this case, we may have a special look, but first we need a good way that we can apply to several cases.

Edit: I want to show my friendly 404 page, which I already have for the general case.

+3
source share
3 answers

You should throw an HttpException 404:

throw new HttpException(404, "Page not Found");
+8
source

EDIT: Apparently, for Darin Dimitrov , what I had before does not work even with customErrors. As Antonio Bakula said in another answer, you should do:

throw new HttpException(404, "Not found")

Then customErrors will be executed.

There, the built-in helper method is called HttpNotFound, so you can just do:

  return HttpNotFound (); Strike>

You can also explicitly return 404 with HttpStatusCodeResult:

  return a new HttpStatusCodeResult (404); Strike>

HttpStatusCodeResultUseful if you don’t need a specific helper method or class for the code you want. Strike>

You should also have this in your Web.config:

<customErrors>
    <error statusCode="404" redirect="~/Custom404Page.html"/>
</customErrors>

defaultRedirect.

+5

HttpStatusCodeResult.

return new httpStatusCodeResult(404);
+1

All Articles