我们想要处理 403 错误、404 错误以及由于以下原因导致的所有错误MySpecialDomainException
并为所有其他错误(包括 IIS 配置中的错误!)提供默认错误页面。所有错误都应该返回正确的 Razor 视图,如果有一个ErrorController
在视图前面。E.g.像这样的东西:
public class ErrorController : Controller
{
public ViewResult NotFound () { return View(); }
public ViewResult Forbidden () { return View(); }
public ViewResult Default ()
{
var ex = ObtainExceptionFromSomewhere();
if(ex is MySpecialDomainException)
return View("MySpecialDomainException", new ErrorModel { Exception = ex });
return View("GeneralError", new ErrorModel { Exception = ex });
}
}
目前,您可以在 www 上找到许多不同的方法来做到这一点,其中一些很可能已经过时了。在这些:
- 控制器.OnException()
- 错误过滤器
- web.config 中的 customErrors 元素
- Global.asax 的 Application_Error 中的处理
Q1:使用 ASP.NET MVC 5 满足我们的要求的推荐方法是什么?
我们还希望捕获 IIS 主机中发生的错误。Q2:为了防止 IIS 必须处理任何 404,我们考虑添加一个与所有可能的 URL 相匹配的默认路由 - 这值得推荐吗?最好也注册 IIS 的 404?
Q3:是否甚至可以注册返回到控制器的 IIS 错误页面,或者 IIS 是否仅支持 ASPX/静态 HTML?
最好的方法是使用 Global.Asax,因为您可以管理所有类型的错误(Ajax 调用/所有意外错误)。与其他人你做不到。
像这样:
protected void Application_Error()
{
HttpContext httpContext = HttpContext.Current;
if (httpContext != null)
{
RequestContext requestContext = ((MvcHandler)httpContext.CurrentHandler).RequestContext;
/* When the request is ajax the system can automatically handle a mistake with a JSON response.
Then overwrites the default response */
if (requestContext.HttpContext.Request.IsAjaxRequest())
{
httpContext.Response.Clear();
string controllerName = requestContext.RouteData.GetRequiredString("controller");
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(requestContext, controllerName);
ControllerContext controllerContext = new ControllerContext(requestContext, (ControllerBase)controller);
JsonResult jsonResult = new JsonResult
{
Data = new { success = false, serverError = "500" },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
jsonResult.ExecuteResult(controllerContext);
httpContext.Response.End();
}
else
{
httpContext.Response.Redirect("~/Error");
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)