ASP.NETMVC中API异常过滤器在异常时返回200响应代码。
创始人
2024-09-19 08:30:41
0

可以通过重写 ExceptionFilterAttribute 类的 OnException 方法来实现在 API 异常时返回正确的 HTTP 响应代码。

以下是代码示例:

public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception != null)
        {
            // 根据异常类型设置要返回的 HTTP 响应代码
            var responseCode = HttpStatusCode.InternalServerError;

            if (context.Exception is AccessDeniedException)
            {
                responseCode = HttpStatusCode.Forbidden;
            }
            else if (context.Exception is NotFoundException)
            {
                responseCode = HttpStatusCode.NotFound;
            }

            // 创建 HttpResponseMessage 对象并设置要返回的 HTTP 响应代码
            var response = context.Request.CreateResponse(responseCode);

            // 将错误信息写入响应体中
            response.Content = new StringContent(context.Exception.Message);

            // 替换执行结果为新的 HttpResponseMessage 对象
            context.Response = response;
        }
    }
}

使用方法:

可以将 CustomExceptionFilterAttribute 属性添加到 API 控制器中的某个方法上,以使该方法调用后产生的异常能够被过滤器捕获并返回正确的 HTTP 响应代码。

例如:

[CustomExceptionFilter]
public IHttpActionResult Get(int id)
{
    var result = service.GetData(id);

    if (result == null)
    {
        throw new NotFoundException("Data not found.");
    }

    return Ok(result);
}

相关内容

热门资讯

透视法子!pokemmo修改器... 透视法子!pokemmo修改器手机版(WePoKer手机版)切实真的是有辅助工具(哔哩哔哩)1、许多...
透视经验!hhpoker有没有... 透视经验!hhpoker有没有作必弊挂(HHpoker透视器)一直有辅助app(哔哩哔哩)1、每一步...
透视烘培!WePOker有没有... 透视烘培!WePOker有没有透视方法(AApoker ai插件)一贯有辅助技巧(哔哩哔哩)1、用户...
透视举措!hhpoker软件安... 透视举措!hhpoker软件安装包(德普之星免费)本来是真的有辅助工具(哔哩哔哩)1、打开软件启动之...
透视窍门!hhpoker是真的... 透视窍门!hhpoker是真的吗(德普之星透视辅助)都是是有辅助方法(哔哩哔哩)运德普之星透视辅助辅...
透视演示!wepoker私人局... 透视演示!wepoker私人局辅助(WPK工具)都是真的是有辅助脚本(哔哩哔哩)透视演示!wepok...
透视要领!wepoker免费透... 透视要领!wepoker免费透视脚本(WePoKer看底牌)果然是有辅助工具(哔哩哔哩)1、实时we...
透视大纲!hh poker软件... 透视大纲!hh poker软件(HHpoker控制)真是有辅助插件(哔哩哔哩);1、hh poker...
透视秘籍!德普之星私人局透视(... 透视秘籍!德普之星私人局透视(德普之星透视辅助)本来存在有辅助脚本(哔哩哔哩)德普之星私人局透视透视...
透视要领!德普之星怎么设置埋牌... 透视要领!德普之星怎么设置埋牌(WPK俱乐部)一直真的是有辅助神器(哔哩哔哩)1)德普之星怎么设置埋...