我正在处理异常,并编写了以下代码。
Web.Config
<customErrors mode="On"></customErrors>
代码更改
public class CustomExceptionFilter : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
//_logger.Error("Uncaught exception", filterContext.Exception);
ViewResult view = new ViewResult();
view.ViewName = "Error";
filterContext.Result = view;
// Prepare the response code.
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
Global.asax
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
// To handle exceptions
GlobalFilters.Filters.Add(new CustomExceptionFilter());
var unityContainer = ModelContainer.Instance;
DependencyResolver.SetResolver(new UnityDependencyResolver(unityContainer));
}
错误视图
@*@model System.Web.Mvc.HandleErrorAttribute*@
<div class="row">
<div class="col-sm-12">
<h1>Error</h1>
<div class="col-sm-12">
<h2>An error occurred while processing your request.</h2>
</div>
</div>
</div>
在我的错误页面中,我想显示异常信息。 此外,如果存在404错误,我还有一个要求需要显示不同的消息。