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条回答
何必那么认真
2楼-- · 2019-01-30 06:02

I've used this:

Response.StatusCode = 404;
return null;
查看更多
爷、活的狠高调
3楼-- · 2019-01-30 06:05

If you are working with .NET Core, you can return NotFound()

查看更多
Ridiculous、
4楼-- · 2019-01-30 06:08

I use:

Response.Status = "404 NotFound";

This works for me :-)

查看更多
该账号已被封号
5楼-- · 2019-01-30 06:09

In MVC 4 and above you can use the built-in HttpNotFound helper methods:

if (notWhatIExpected)
{
    return HttpNotFound();
}

or

if (notWhatIExpected)
{
    return HttpNotFound("I did not find message goes here");
}
查看更多
手持菜刀,她持情操
6楼-- · 2019-01-30 06:13

In .NET Core 1.1:

return new NotFoundObjectResult(null);
查看更多
手持菜刀,她持情操
7楼-- · 2019-01-30 06:14

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");
查看更多
登录 后发表回答