asp.net-mvc 在 Asp.net MVC 中抛出/返回 404 actionresult 或异常并让 IIS 处理它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1998328/
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
throwing/returning a 404 actionresult or exception in Asp.net MVC and letting IIS handle it
提问by CVertex
how do I throw a 404 or FileNotFound exception/result from my action and let IIS use my customErrors config section to show the 404 page?
如何从我的操作中抛出 404 或 FileNotFound 异常/结果并让 IIS 使用我的 customErrors 配置部分来显示 404 页面?
I've defined my customErrors like so
我已经像这样定义了我的 customErrors
<customErrors mode="On" defaultRedirect="/trouble">
<error statusCode="404" redirect="/notfound" />
</customErrors>
My first attempt at an actionResult that tries to add this doesnt work.
我第一次尝试尝试添加它的 actionResult 不起作用。
public class NotFoundResult : ActionResult {
public NotFoundResult() {
}
public override void ExecuteResult(ControllerContext context) {
context.HttpContext.Response.TrySkipIisCustomErrors = false;
context.HttpContext.Response.StatusCode = 404;
}
}
But this just shows a blank page and not my /not-found page
但这只是显示一个空白页面而不是我的 /not-found 页面
:(
:(
What should I do?
我该怎么办?
回答by Rob Levine
ASP.NET MVC 3 introduced the HttpNotFoundResultaction result which should be used in preference to manually throwing the exception with the http status code. This can also be returned via the Controller.HttpNotFoundmethod on the controller:
ASP.NET MVC 3 引入了HttpNotFoundResult操作结果,它应该优先用于手动抛出带有 http 状态代码的异常。这也可以通过控制器上的Controller.HttpNotFound方法返回:
public ActionResult MyControllerAction()
{
...
if (someNotFoundCondition)
{
return HttpNotFound();
}
}
Prior to MVC 3 you had to do the following:
在 MVC 3 之前,您必须执行以下操作:
throw new HttpException(404, "HTTP/1.1 404 Not Found");
回答by Simon
You can call Controller.HttpNotFound
你可以调用 Controller.HttpNotFound
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.httpnotfound(v=vs.98).aspx
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.httpnotfound(v=vs.98).aspx
if (model == null)
{
return HttpNotFound();
}
回答by tugberk
This could help as well;
这也有帮助;
ASP.NET MVC : Throwing 404 Exceptions Manually From Controller When Model is Null

