异常过滤器在Web API中不起作用 [英] Exception filter not working in web api
问题描述
我有一个自定义的异常过滤器,能够处理控制器中的所有错误(只是一种常见的错误处理机制),
I have a custom exception filter capable handle all the errors in the controller( just a common error handling mechanism) ,
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文件
I registered this filter in fillterConfig file
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ExceptionHandlingAttribute());
filters.Add(new HandleErrorAttribute());
}
但是我遇到错误
给定的筛选器实例必须实现以下一个或多个筛选器接口:IAuthorizationFilter,IActionFilter,IResultFilter,IExceptionFilter
我知道ExceptionFilterAttribute已经隐含了IExceptionFilter过滤器.为什么我会收到此错误
I know the ExceptionFilterAttribute already implimented IExceptionFilter filter. Why i am getting this error
推荐答案
为此,您需要实现System.Web.Http.Filters.ExceptionFilterAttribute.
In order for this to work, you need to implement 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中,注册过滤器:
Then, in your WebApiConfig.cs, register the filter:
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());
}
这篇关于异常过滤器在Web API中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!