C# 如何使用 asp.net mvc 视图返回 404
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13764685/
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 return 404 with asp.net mvc view
提问by user1615362
How do I achieve the below functionality?
如何实现以下功能?
My controler:
我的控制器:
if (something == null)
{
//return the view with 404 http header
return View();
}
//return the view with 200 http header
return View();
采纳答案by fero
Just write
写就好了
Response.StatusCode = 404;
before returning the view.
在返回视图之前。
回答by levelnis
if (something == null)
{
return HttpNotFound();
}
return View();
回答by dsgriffin
if (something == null)
{
return new HttpNotFoundResult(); // 404
}
else
{
return new HttpStatusCodeResult(HttpStatusCode.OK); // 200
}
回答by Alan Low
if (something == null)
{
Response.StatusCode = (int)HttpStatusCode.NotFound;
return View();
}
//return the view with 200 http header
return View();
回答by VJAI
I would throw a 404 exception and create a custom exception filter that return a not found page for 404 errors. The built-in HandleErrorfilter doesn't handle 404 errors.
我会抛出一个 404 异常并创建一个自定义异常过滤器,该过滤器为 404 错误返回一个未找到的页面。内置HandleError过滤器不处理 404 错误。
if (something == null)
{
throw new HttpException(404, "Not found")
}
return View();
回答by Medeni Baykal
You should set TrySkipIisCustomErrorsproperty of Responseas true.
您应该将TrySkipIisCustomErrors属性设置为Responseas true。
public ActionResult NotFound()
{
Response.StatusCode = 404;
Response.TrySkipIisCustomErrors = true;
return View();
}

