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

相关内容

热门资讯

透视科技!aapoker真的假... 透视科技!aapoker真的假的(透视)aapoker透视方法,可靠教程(有挂详情);透视科技!aa...
透视ai代打!aapoker公... 透视ai代打!aapoker公共底牌(透视)aapoker破解侠是真的吗,2025新版总结(有挂方法...
透视神器!aapoker怎么设... 透视神器!aapoker怎么设置抽水(透视)aapoker透视脚本,可靠教程(有挂详情)一、aapo...
透视攻略!aapoker怎么控... 透视攻略!aapoker怎么控制牌(透视)aapoker透视插件,可靠教程(有挂辅助)1、首先打开a...
透视透视挂!aapoker插件... 透视透视挂!aapoker插件(透视)aapoker发牌逻辑,可靠教程(有挂辅助)1、aapoker...
透视脚本!aapoker破解侠... 透视脚本!aapoker破解侠是真的吗(透视)aapoker ai插件,黑科技教程(有挂工具);1、...
透视脚本!aapoker怎么设... 透视脚本!aapoker怎么设置提高好牌几率(透视)aapoker透视脚本下载,揭秘攻略(有挂攻略)...
透视ai代打!aapoker免... 透视ai代打!aapoker免费透视脚本(透视)aapoker辅助怎么用,2025新版总结(有挂方法...
透视总结!aa poker透视... 透视总结!aa poker透视软件(透视)aapoker破解侠是真的吗,透明教程(有挂脚本);1、任...
透视好牌!aapoker透视方... 透视好牌!aapoker透视方法(透视)aapoker插件下载,AA德州教程(有挂解说)aapoke...