我有一个自定义异常过滤器,能够处理控制器中的所有错误(只是一个常见的错误处理机制),
public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
var error = actionExecutedContext.Exception;
if (error is BussinessExcetion)
{
var exceptionBase = (BussinessExcetion)error;
var code = (HttpStatusCode)exceptionBase.HttpExceptionCode;
throw new HttpResponseException(new HttpResponseMessage(code)
{
Content = new StringContent(exceptionBase.Message),
ReasonPhrase = "Exception"
,
});
}
// Now log the error
/* Error logging */
LoggingFactory.GetLogger().LogError(string.Format("Exception:{0} ||Stack trace:{1}", error.Message, error.StackTrace), error);
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An error occurred, contact the support team."),
ReasonPhrase = "Critical Exception"
});
}
}
我在 fillterConfig 文件中注册了这个过滤器
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ExceptionHandlingAttribute());
filters.Add(new HandleErrorAttribute());
}
但我收到错误
给定的过滤器实例必须实现以下一个或多个过滤器接口:IAuthorizationFilter、IActionFilter、IResultFilter、IExceptionFilter
我知道 ExceptionFilterAttribute 已经实现了 IExceptionFilter 过滤器。为什么我收到此错误
为了使其工作,您需要实现 System.Web.Http.Filters.ExceptionFilterAttribute。
public class NotImplExceptionFilterAttribute : ExceptionFilterAttribute
{
log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public override void OnException(HttpActionExecutedContext context)
{
RequestData requestData = new RequestData(context.Request);
log.Error("NotImplExceptionFilterAttribute", context.Exception);
context.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
}
}
然后,在 WebApiConfig.cs 中注册过滤器:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{count}",
defaults: new { count = RouteParameter.Optional }
);
config.Filters.Add(new NotImplExceptionFilterAttribute());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)