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

相关内容

热门资讯

普及透视!竞技联盟透视插件!果... 普及透视!竞技联盟透视插件!果然是真的有辅助软件(有挂分享)-哔哩哔哩一、竞技联盟透视插件游戏安装教...
解迷透视!wpk辅助购买,xp... 解迷透视!wpk辅助购买,xpoker辅助助手,演示教程(有挂详情)-哔哩哔哩小薇(辅助器软件下载)...
教你透视!sohoopoker... 教你透视!sohoopoker辅助!都是真的是有辅助脚本(有挂技巧)-哔哩哔哩1、起透看视 soho...
解迷透视!wepoker买脚本... 解迷透视!wepoker买脚本靠谱吗,pokerworld修改器,指南书教程(证实有挂)-哔哩哔哩w...
开挂透视!pokemmo手机版... 开挂透视!pokemmo手机版修改器!原来有辅助软件(有挂辅助)-哔哩哔哩1、打开软件启动之后找到中...
解迷透视!wepoker国外版... 解迷透视!wepoker国外版透视,poker world辅助器,手段教程(真的有挂)-哔哩哔哩1、...
关于透视!pokemmo脚本辅... 关于透视!pokemmo脚本辅助器!真是是真的有辅助神器(有挂技巧)-哔哩哔哩1、该软件可以轻松地帮...
详情透视!拱趴大菠萝有挂吗,哈... 详情透视!拱趴大菠萝有挂吗,哈糖大菠萝怎么挂,指南教程(有挂讲解)-哔哩哔哩1、拱趴大菠萝有挂吗免费...
普及透视!红龙poker辅助平... 普及透视!红龙poker辅助平台!真是真的是有辅助方法(有挂头条)-哔哩哔哩1)红龙poker辅助平...
总结透视!wepoker辅助透... 总结透视!wepoker辅助透视,hhpoker为什么一直输,窍门教程(有挂方略)-哔哩哔哩1、游戏...