如何在ExceptionFilterAttribute中返回自定义信息

本文关键字:返回 自定义 信息 ExceptionFilterAttribute | 更新日期: 2023-09-27 17:54:03

项目负责人希望我为我们的Web API创建一个自定义异常过滤器,以捕获所有未处理的异常。我已经在WebApiConfig文件中添加了一个自定义过滤器,它正在工作,但它没有提供他想要的所有细节。他想返回一个500的错误,正文中有这样的信息:

{
  "code": 500,
  "message": "My custom message"
}

下面所示的处理程序代码返回一个500错误,但是代码体只显示

{
  "message": "My custom message"
}

我如何自定义这个来添加"代码"号码,即使这个信息是多余的?

public class UnhandledExceptionAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        string message = "My custom message";
        context.Response = context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message);
    }
}

如何在ExceptionFilterAttribute中返回自定义信息

仅使用CreateResponse<T>扩展方法:

public class UnhandledExceptionAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        string message = "My custom message";
        context.Response = context.Request.CreateResponse(
            HttpStatusCode.InternalServerError,
            new {
                code = 500,
                message = message
            });
    }
}