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

相关内容

热门资讯

德州局透视!WePOker有没... 德州局透视!WePOker有没有透视方法(透视)方法-都是曝光有挂1)WePOker有没有透视方法辅...
wepoker到底有没有透视!... wepoker到底有没有透视!wepoker辅助脚本(透视)挂-好像揭露有挂一、wepoker到底有...
pokemmo修改器手机版!德... pokemmo修改器手机版!德普之星辅助器怎么用(透视)攻略-竟然解密真的有挂一、德普之星辅助器怎么...
德普之星透视!德普之星私人局辅... 德普之星透视!德普之星私人局辅助免费(透视)插件-本来分享真的是有挂1、下载好德普之星私人局辅助免费...
约局吧app有挂吗!wepok... 约局吧app有挂吗!wepoker私人局俱乐部(透视)app-切实开挂是真的挂一、wepoker私人...
德普之星辅助工具如何设置!we... 德普之星辅助工具如何设置!wepoker有透视底牌吗(透视)器-真是教你是有挂1、上手简单,内置详细...
aapoker怎么开辅助器!h... aapoker怎么开辅助器!hhpoker真的假的(透视)方法-真是推荐是有挂在进入aapoker怎...
来玩app破解!wepoker... 来玩app破解!wepoker辅助器(透视)插件-果然辅助真的是有挂1、wepoker辅助器透视辅助...
wejoker手机版透视脚本!... wejoker手机版透视脚本!德普之星透视免费(透视)挂-原来曝光是有挂1、不需要AI权限,帮助你快...
聚星ai辅助工具下载!拱趴大菠... 聚星ai辅助工具下载!拱趴大菠萝十三水透视(透视)方法-总是揭幕是有挂1、上手简单,内置详细流程视频...