如何从我的操作中抛出404或FileNotFound异常/结果并让IIS使用我的customErrors配置部分来显示404页面?
我已经定义了我的customErrors
<customErrors mode="On" defaultRedirect="/trouble">
<error statusCode="404" redirect="/notfound" />
</customErrors>
我第一次尝试添加此功能的actionResult无效。
public class NotFoundResult : ActionResult {
public NotFoundResult() {
}
public override void ExecuteResult(ControllerContext context) {
context.HttpContext.Response.TrySkipIisCustomErrors = false;
context.HttpContext.Response.StatusCode = 404;
}
}
但这只是显示一个空白页而不是我/未找到的页面
:(
我该怎么办?
答案 0 :(得分:130)
ASP.NET MVC 3引入了HttpNotFoundResult操作结果,应该优先使用http状态代码手动抛出异常。 这也可以通过控制器上的Controller.HttpNotFound方法返回:
public ActionResult MyControllerAction()
{
...
if (someNotFoundCondition)
{
return HttpNotFound();
}
}
在MVC 3之前,您必须执行以下操作:
throw new HttpException(404, "HTTP/1.1 404 Not Found");
答案 1 :(得分:6)
您可以调用Controller.HttpNotFound
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.httpnotfound(v=vs.98).aspx
if (model == null)
{
return HttpNotFound();
}
答案 2 :(得分:2)