views:

219

answers:

3

I have an action that takes in a string that is used to retrieve some data. If this string results in no data being returned (maybe because it has been deleted), I want to return a 404 and display an error page.

I currently just use return a special view that display a friendly error message specific to this action saying that the item was not found. This works fine, but would ideally like to return a 404 status code so search engines know that this content no longer exists and can remove it from the search results.

What is the best way to go about this?

Is it as simple as setting Response.StatusCode = 404?

+4  A: 

There are multiple ways to do it,

  1. You are right in common aspx code it can be assigned in your specified way
  2. throw new HttpException(404, "Some description");
Dewfy
One thing to watch out for is that if you have a customError page set up to handle 404 then this error page will return 200 (the not found page was found... :-( ). I tend to throw the exception from say BlogController and have the NotFound action set the proper response code.
Nigel Sampson
I ended up doing:Response.StatusCode = 404;Response.TrySkipIisCustomErrors = true;return View("MyCustomView");This works perfectly in my situation.
zaph0d
+1  A: 

I use:

Response.Status = "404 NotFound";

This works for me :-)

bruno
+2  A: 

In NerdDinner eg. Try it

public ActionResult Details(int? id) {
    if (id == null) {
        return new FileNotFoundResult { Message = "No Dinner found due to invalid dinner id" };
    }
    ...
}
cem
Thanks, but behind the scenes, that throws an HttpException similar to suggestion number two in Dewfy's post. I am looking for a bit more control so I can display a nice error page specific to the action, not just redirecting to the controller / global 404 page. Looks as though setting the status code and returning to a custom view is the way to go for my situation.
zaph0d