gpt4 book ai didi

c# - 异常过滤器在 web api 中不起作用

转载 作者:太空狗 更新时间:2023-10-29 21:27:54 25 4
gpt4 key购买 nike

我有一个自定义异常过滤器能够处理 Controller 中的所有错误(只是一个常见的错误处理机制),

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());

}

但是我收到一个错误

给定的过滤器实例必须实现以下一个或多个过滤器接口(interface):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());
}

关于c# - 异常过滤器在 web api 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21494018/

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