Asp.net MVC 自定义错误页面以及return HttpNotFound遇到的问题

时间:2022-03-08 11:07:03

今天在处理mvc 项目404和500页面时,发现我以前比较喜欢用的Return HttpNotFound()没有跳转到我在webconfig中配置的自定义404页面,而且也不会去执行Global中的Application_Error方法,经过一番查阅资料,发现这个问题得去想别的办法去做,具体的做法有三种,如下:

1.放弃Return HttpNotFound(),适用throw new HttpException(404, "page not found");

2.让所有的Controller继承自BaseController,然后BaseController重写HttpNotFound方法,代码如下:

        protected override HttpNotFoundResult HttpNotFound(string statusDescription)
{
this.Response.StatusCode = ;
this.Response.TrySkipIisCustomErrors = true;
Response.Clear();
Response.Redirect("~/FileNotFound.html");
Response.End();
return null;
}

3.使用Fliter来处理异常,代码如下;

 public class CustomViewForHttpStatusResultFilter : IResultFilter, IExceptionFilter
{
string viewName;
int statusCode; #region Ctor
public CustomViewForHttpStatusResultFilter(HttpStatusCodeResult prototype, string viewName)
: this(prototype.StatusCode, viewName)
{
} public CustomViewForHttpStatusResultFilter(int statusCode, string viewName)
{
this.viewName = viewName;
this.statusCode = statusCode;
}
#endregion public void OnResultExecuted(ResultExecutedContext filterContext)
{
HttpStatusCodeResult httpStatusCodeResult = filterContext.Result as HttpStatusCodeResult;
//比较重要的一句,当请求完成后,发现
if (httpStatusCodeResult != null && httpStatusCodeResult.StatusCode == statusCode)
{
ExecuteCustomViewResult(filterContext.Controller.ControllerContext); }
} public void OnResultExecuting(ResultExecutingContext filterContext)
{
} public void OnException(ExceptionContext filterContext)
{
HttpException httpException = filterContext.Exception as HttpException; if (httpException != null && httpException.GetHttpCode() == statusCode)
{
ExecuteCustomViewResult(filterContext.Controller.ControllerContext);
// This causes ELMAH not to log exceptions, so commented out
//filterContext.ExceptionHandled = true;
}
} void ExecuteCustomViewResult(ControllerContext controllerContext)
{
ViewResult viewResult = new ViewResult();
viewResult.ViewName = viewName;
viewResult.ViewData = controllerContext.Controller.ViewData;
viewResult.TempData = controllerContext.Controller.TempData;
viewResult.ExecuteResult(controllerContext);
controllerContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}