asp.net-mvc 如何让MVC动作返回404
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2948484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get MVC action to return 404
提问by Paul Hiles
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.
我有一个动作,它接受一个用于检索一些数据的字符串。如果这个字符串导致没有数据返回(可能是因为它已被删除),我想返回一个 404 并显示一个错误页面。
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.
我目前只使用返回一个特殊视图,该视图显示特定于此操作的友好错误消息,说明未找到该项目。这工作正常,但理想情况下希望返回 404 状态代码,以便搜索引擎知道此内容不再存在并可以将其从搜索结果中删除。
What is the best way to go about this?
解决这个问题的最佳方法是什么?
Is it as simple as setting Response.StatusCode = 404?
是否像设置 Response.StatusCode = 404 一样简单?
采纳答案by Dewfy
There are multiple ways to do it,
有多种方法可以做到,
- You are right in common aspx code it can be assigned in your specified way
throw new HttpException(404, "Some description");
- 您在常见的 aspx 代码中是正确的,它可以以您指定的方式分配
throw new HttpException(404, "Some description");
回答by Stefan Paul Noack
In ASP.NET MVC 3 and above you can return a HttpNotFoundResultfrom the controller.
在 ASP.NET MVC 3 及更高版本中,您可以从控制器返回HttpNotFoundResult。
return new HttpNotFoundResult("optional description");
回答by Gone Coding
In MVC 4 and above you can use the built-in HttpNotFound
helper methods:
在 MVC 4 及更高版本中,您可以使用内置的HttpNotFound
辅助方法:
if (notWhatIExpected)
{
return HttpNotFound();
}
or
或者
if (notWhatIExpected)
{
return HttpNotFound("I did not find message goes here");
}
回答by Sinan BARAN
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>
回答by Wout
I've used this:
我用过这个:
Response.StatusCode = 404;
return null;
回答by Robert Paulsen
If you are working with .NET Core, you can return NotFound()
如果您正在使用 .NET Core,则可以 return NotFound()
回答by cem
回答by ganders
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();
}
回答by bruno
I use:
我用:
Response.Status = "404 NotFound";
This works for me :-)
这对我有用:-)
回答by feedthedogs
In .NET Core 1.1:
在 .NET Core 1.1 中:
return new NotFoundObjectResult(null);