John-Philip
John-Philip

Reputation: 617

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

I have implemented 404 handling for the general case in ASP.NET MVC 3, for when a controller/view is not found. But how should it be handled inside the controller if the user is trying to access something that can't be found? For example www.foo.bar/Games/Details/randomjunk will call this inside GamesController:

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

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

We could have a special view in this case, but to start with we need a good way we can apply to several cases.

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

Upvotes: 3

Views: 6900

Answers (3)

Arjan Einbu
Arjan Einbu

Reputation: 13692

You could return a HttpStatusCodeResult.

return new httpStatusCodeResult(404);

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 285077

EDIT: Apparently per Darin Dimitrov, what I had before doesn't work even with customErrors. As Antonio Bakula says in the other answer, you have to do:

throw new HttpException(404, "Not found")

Then the customErrors will work.

There's a built-in helper method called HttpNotFound so you can just do:

return HttpNotFound();

You could also explicitly return a 404 with HttpStatusCodeResult:

return new HttpStatusCodeResult(404);

HttpStatusCodeResult is helpful when there's not a specific helper method or class for the code you want.

You should also have this in your Web.config:

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

You can also have additional lines for other statuses, and a defaultRedirect.

Upvotes: 5

Antonio Bakula
Antonio Bakula

Reputation: 20693

You should throw HttpException 404 :

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

Upvotes: 9

Related Questions