简体   繁体   English

异常过滤器在 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"
                                                });
        }
    }

I registered this filter in fillterConfig file我在 fillterConfig 文件中注册了这个过滤器

 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ExceptionHandlingAttribute());
     filters.Add(new HandleErrorAttribute());

    }

but i am getting an error但我收到一个错误

The given filter instance must implement one or more of the following filter interfaces: IAuthorizationFilter, IActionFilter, IResultFilter, IExceptionFilter给定的过滤器实例必须实现以下一个或多个过滤器接口:IAuthorizationFilter、IActionFilter、IResultFilter、IExceptionFilter

I know the ExceptionFilterAttribute already implimented IExceptionFilter filter.我知道 ExceptionFilterAttribute 已经实现了 IExceptionFilter 过滤器。 Why i am getting this error为什么我收到这个错误

In order for this to work, you need to implement System.Web.Http.Filters.ExceptionFilterAttribute.为了使其工作,您需要实现 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);
    }
}

Then, in your WebApiConfig.cs, register the filter:然后,在您的 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());
    }

And for anyone using NLog:对于任何使用 NLog 的人:

public class NlogExceptionFilter : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext filterContext)
    {
        Exception lastException = filterContext.Exception;
        Logger logger = LogManager.GetLogger("");
        logger.Fatal(lastException.Message, lastException);
    }
}

And in the WebApiConfig.cs并在WebApiConfig.cs 中

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new NlogExceptionFilter());
    ...
}

make sure you also override the Async version of the filter确保您还覆盖了过滤器的异步版本

class myFilter : ExceptionFilterAttribute
{
...
    public override async Task OnExceptionAsync(HttpActionExecutedContext ctx, 
                                                CancellationToken cancellationToken)
    {
    ...
    }
...
}

Doh!哦! If you're like me, and were handling the exception in your controller, then you would not be triggering the filter.如果你像我一样,在你的控制器中处理异常,那么你就不会触发过滤器。 Inside your catch block, place a throw.在你的 catch 块内,放置一个投掷。 Voila!瞧!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM