How to get MVC action to return 404

2019-01-30 05:52发布

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?

12条回答
ゆ 、 Hurt°
2楼-- · 2019-01-30 06:15

Code :

if (id == null)
{
  throw new HttpException(404, "Your error message");//RedirectTo NoFoundPage
}

Web.config

<customErrors mode="On">
  <error statusCode="404" redirect="/Home/NotFound" />
</customErrors>
查看更多
Viruses.
3楼-- · 2019-01-30 06:21

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" };
    }
    ...
}
查看更多
Root(大扎)
4楼-- · 2019-01-30 06:23

You can also do:

        if (response.Data.IsPresent == false)
        {
            return StatusCode(HttpStatusCode.NoContent);
        }
查看更多
ら.Afraid
5楼-- · 2019-01-30 06:23

Please try the following demo code:

public ActionResult Test()

{
  return new HttpStatusCodeResult (404,"Not found");
}
查看更多
Viruses.
6楼-- · 2019-01-30 06:28

In ASP.NET MVC 3 and above you can return a HttpNotFoundResult from the controller.

return new HttpNotFoundResult("optional description");
查看更多
相关推荐>>
7楼-- · 2019-01-30 06:28

None of the above examples worked for me until I added the middle line below:

public ActionResult FourOhFour()
{
    Response.StatusCode = 404;
    Response.TrySkipIisCustomErrors = true; // this line made it work
    return View();
}
查看更多
登录 后发表回答