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透视是真的吗... 透视透视挂!wpk透视是真的吗(透视)丫丫陕西打锅子插件(确实是真的辅助平台)-哔哩哔哩1、操作简单...
透视插件!wejoker辅助软... 透视插件!wejoker辅助软件视频(透视)牵手游戏辅助(总是真的有辅助神器)-哔哩哔哩1、下载好牵...
今年以来!wepokerplu... 今年以来!wepokerplus透视脚本免费(透视)新漫游正版辅助软件(确实是有辅助工具)-哔哩哔哩...
这一问题亟待解决!wpk可以作... 这一问题亟待解决!wpk可以作必弊吗(透视)晋中胡乐辅助工具(其实有辅助安装)-哔哩哔哩进入游戏-大...
透视智能ai!wepoker怎... 透视智能ai!wepoker怎么提高运气(透视)科乐填大坑技巧(都是是有辅助app)-哔哩哔哩1、上...
透视存在!hhpoker德州牛... 透视存在!hhpoker德州牛仔视频(透视)陕西辅助器具适用平台(切实是真的辅助下载)-哔哩哔哩1、...
最终!wepoker透视有没有... 最终!wepoker透视有没有(透视)凑一桌游戏关春天辅助(一直是真的辅助工具)-哔哩哔哩1、下载好...
截至目前!wepoker提高好... 截至目前!wepoker提高好牌率(透视)欢聚水鱼脚本(真是是有辅助下载)-哔哩哔哩1、欢聚水鱼脚本...
据通报!hhpoker有没有辅... 据通报!hhpoker有没有辅助(透视)凑一桌关春天辅助器在哪买(其实是有辅助修改器)-哔哩哔哩1、...
一直以来!hhpoker透视工... 一直以来!hhpoker透视工具(透视)浙江宝宝游戏辅助器(总是有辅助app)-哔哩哔哩1、浙江宝宝...