因此,如果我正确地理解了[HandleError],(see here),您必须将它添加到每个您希望处理错误的控制器中。
只需将错误页面的路径添加到web.config customErrors标记中似乎要容易得多:
<customErrors mode="On" defaultRedirect="~/Error/Index" >
</customErrors>在什么情况下使用HandleError会比这更好?
发布于 2010-10-06 23:48:31
在[HandleError]中,您可以实现很多功能。您可以记录错误。您还可以找出错误的类型,并根据情况将用户重定向到某个page.Following是一个示例-
public class HandleErrorAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled)
return;
string referrerController = string.Empty;
string referrerAction = string.Empty;
if (filterContext.HttpContext.Request.UrlReferrer != null)
{
string[] segments = filterContext.HttpContext.Request.UrlReferrer.Segments;
if (segments.Length > 1)
{
referrerController = segments[1] != null ? segments[1].Replace("/", string.Empty) : string.Empty;
}
if (segments.Length > 2)
{
referrerAction = segments[2] != null ? segments[2].Replace("/", string.Empty) : string.Empty;
}
}
filterContext.Controller.TempData["exception"] = filterContext.Exception.Message;
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(
new { controller = referrerController , action = referrerAction}));
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
}
}在这段代码中,我将异常消息保存到TempData,这样我就可以向用户显示错误消息。这只是一个例子,但是你可以根据你的需求做任何事情。在这里,我通过继承FilterAttribute并实现IExceptionFilter来创建我自己的[HandleError]属性。你可以看到我在这里得到的力量。我实现了我自己的属性来处理我的需求。但是您可以使用内置的[HandleError]来实现类似的结果。
第2行的目的是处理链中的其他人已经处理了异常的情况。那么,在这种情况下,您可能没有兴趣再次处理它。Response.Clear()用于在我将用户重定向到新页面之前清除管道。在你的情况下,没有必要去那里。
发布于 2015-11-02 19:55:12
任何属性都可以全局应用于FilterConfig.RegisterGlobalFilters中的所有控制器: filters.Add(new HandleErrorAttribute());
在相关的方法中,也可以对API控制器这样做,即WebApiConfig.Register。
但是,如果您只需要显示一个简单的错误页面,只需使用customErrors即可。
https://stackoverflow.com/questions/3874278
复制相似问题