Asp.net-Mvc
在 Asp.net MVC 中拋出/返回 404 actionresult 或異常並讓 IIS 處理它
如何從我的操作中引發 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; } }但這只是顯示一個空白頁面,而不是我的 /not-found 頁面
:(
我該怎麼辦?
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");