gpt4 book ai didi

asp.net - 设置 Web API ExceptionFilterAttribute 中处理的异常

转载 作者:行者123 更新时间:2023-12-02 03:20:02 25 4
gpt4 key购买 nike

ASP.NET Web API 中是否有任何方法可以将异常标记为在 ExceptionFilterAttribute 中处理?

我想使用异常过滤器在方法级别处理异常,并停止传播到全局注册的异常过滤器。

Controller 操作上使用的过滤器:

public class MethodExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is NotImplementedException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(context.Exception.Message)
};
// here in MVC you could set context.ExceptionHandled = true;
}
}
}

全局注册的过滤器:

public class GlobalExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is SomeOtherException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.SomethingElse)
{
Content = new StringContent(context.Exception.Message)
};
}
}
}

最佳答案

尝试抛出 HttpResponseException在本地处理结束时。按照设计,它们不会被异常过滤器捕获。

throw new HttpResponseException(context.Response);

关于asp.net - 设置 Web API ExceptionFilterAttribute 中处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16441934/

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