gpt4 book ai didi

c# - ASP.net MVC - 自定义 HandleError Filter - 根据异常类型指定 View

转载 作者:IT王子 更新时间:2023-10-29 03:56:20 28 4
gpt4 key购买 nike

我在我的 MVC 应用程序中继承了 HandleErrorAttribute,因此我可以记录错误:

public class HandleAndLogErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
base.OnException(filterContext);

if( filterContext.Exception != null )
{
// log here
}
}
}

我将其添加为全局过滤器:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleAndLogErrorAttribute());
}

是否也可以为特定的异常类型指定自定义 View ?例如:

if( filterContext.Exception is DivideByZeroException )
{
// how do i specify that the view should be DivideByZero?
}

最佳答案

  1. 创建一个继承HandleErrorAttribute(或直接实现IExceptionFilter)的新过滤器
  2. 在 global.asax 中注册它(通过替换 filters.Add(new HandleError());):

这是我创建的一个过滤器,它尝试根据特定的 HTTP 状态代码查找 View :

public class MyErrorHandler : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled || !filterContext.HttpContext.IsCustomErrorEnabled)
return;

var statusCode = (int) HttpStatusCode.InternalServerError;
if (filterContext.Exception is HttpException)
{
statusCode = filterContext.Exception.As<HttpException>().GetHttpCode();
}
else if (filterContext.Exception is UnauthorizedAccessException)
{
//to prevent login prompt in IIS
// which will appear when returning 401.
statusCode = (int)HttpStatusCode.Forbidden;
}
_logger.Error("Uncaught exception", filterContext.Exception);

var result = CreateActionResult(filterContext, statusCode);
filterContext.Result = result;

// Prepare the response code.
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = statusCode;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}

protected virtual ActionResult CreateActionResult(ExceptionContext filterContext, int statusCode)
{
var ctx = new ControllerContext(filterContext.RequestContext, filterContext.Controller);
var statusCodeName = ((HttpStatusCode) statusCode).ToString();

var viewName = SelectFirstView(ctx,
"~/Views/Error/{0}.cshtml".FormatWith(statusCodeName),
"~/Views/Error/General.cshtml",
statusCodeName,
"Error");

var controllerName = (string) filterContext.RouteData.Values["controller"];
var actionName = (string) filterContext.RouteData.Values["action"];
var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
var result = new ViewResult
{
ViewName = viewName,
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
};
result.ViewBag.StatusCode = statusCode;
return result;
}

protected string SelectFirstView(ControllerContext ctx, params string[] viewNames)
{
return viewNames.First(view => ViewExists(ctx, view));
}

protected bool ViewExists(ControllerContext ctx, string name)
{
var result = ViewEngines.Engines.FindView(ctx, name, null);
return result.View != null;
}
}

关于c# - ASP.net MVC - 自定义 HandleError Filter - 根据异常类型指定 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8144695/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com