ApiController并不总是在BadRequest中返回数据

时间:2019-05-03 16:39:17

标签: c# asp.net-core asp.net-core-mvc asp.net-core-2.2

我正在使用ASP.NET Core 2.2 ApiController,并且具有以下内容:

[ApiController]
public class PostController : Controller {
  [HttpGet("posts")]
  public async Task<IActionResult> Get() {
    return BadRequest();
  }
}

在这种情况下,我得到以下响应:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "Bad Request",
  "status": 400,
  "traceId": "0HLMFSL0C7SKB:00000001"
}

但是如果我返回如下数据:

[ApiController]
public class PostController : Controller {
  [HttpGet("posts")]
  public async Task<IActionResult> Get() {
    List<String> errors = new List<String> { "Code is invalid" };
    return BadRequest(new { errors = errors });
  }
}

我得到以下信息:

{
  "errors": ["Code is invalid"]
}

为什么没有内容返回时ApiController会添加类型,标题,状态和traceId?

我希望响应始终像这样:

{
  "errors": ["Code is invalid"],
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "Bad Request",
  "status": 400,
  "traceId": "0HLMFSL0C7SKB:00000001"
}

4 个答案:

答案 0 :(得分:1)

默认ControllerBase.BadRequest()响应内容是因为您已将[ApiController]属性应用于控制器。在线记录如下:

https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2#problem-details-for-error-status-codes

  

当兼容版本为2.2或更高版本时,MVC会将错误结果(状态码为400或更高的结果)转换为ProblemDetails的结果。 ProblemDetails类型基于RFC 7807规范,用于在HTTP响应中提供机器可读的错误详细信息。

这包括typetitle,状态and traceId`值:https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2#problem-details-for-error-status-codes

如果您未应用[ApiController],则ControllerBase.BadRequest()将返回带有HTTP 400状态码的空响应。

接受ControllerBase.BadRequestvalue响应对象的model的所有重载都将被序列化并返回,而不是使用ApiController默认响应。

答案 1 :(得分:1)

对于ProblemDetails,取决于ObjectResult是否继承自IClientErrorActionResult

您可以按照以下步骤进行解决:

  1. MyBadRequestObjectResult

    public class MyBadRequestObjectResult : BadRequestObjectResult, IClientErrorActionResult
    {
        public MyBadRequestObjectResult() : base((object)null)
        {
        }
    
        public MyBadRequestObjectResult(object error) : base(error)
        {
        }
    }
    
  2. 自定义ProblemDetailsErrorFactory

    public class ProblemDetailsErrorFactory: IClientErrorFactory
    {
        private static readonly string TraceIdentifierKey = "traceId";
        private static readonly string ErrorsKey = "errors";
        private readonly ApiBehaviorOptions _options;
    
        public ProblemDetailsErrorFactory(IOptions<ApiBehaviorOptions> options)
        {
            _options = options?.Value ?? throw new ArgumentNullException(nameof(options));
        }
    
        public IActionResult GetClientError(ActionContext actionContext, IClientErrorActionResult clientError)
        {
            var problemDetails = new ProblemDetails
            {
                Status = clientError.StatusCode,
                Type = "about:blank",
            };
    
            if (clientError.StatusCode is int statusCode &&
                _options.ClientErrorMapping.TryGetValue(statusCode, out var errorData))
            {
                problemDetails.Title = errorData.Title;
                problemDetails.Type = errorData.Link;
                SetErrors(actionContext, problemDetails);
                SetTraceId(actionContext, problemDetails);
            }
    
            return new ObjectResult(problemDetails)
            {
                StatusCode = problemDetails.Status,
                ContentTypes =
                {
                    "application/problem+json",
                    "application/problem+xml",
                },
            };
        }
        internal static void SetErrors(ActionContext actionContext, ProblemDetails problemDetails)
        {
            if (actionContext is ResultExecutingContext resultExecutingContext)
            {
                if (resultExecutingContext.Result is BadRequestObjectResult result)
                {
                    problemDetails.Extensions[ErrorsKey] = result.Value;
                }
            }
            //var errors = actionContext.HttpContext.
        }
        internal static void SetTraceId(ActionContext actionContext, ProblemDetails problemDetails)
        {
            var traceId = Activity.Current?.Id ?? actionContext.HttpContext.TraceIdentifier;
            problemDetails.Extensions[TraceIdentifierKey] = traceId;
        }
    
    }
    
  3. 注册ProblemDetailsErrorFactory

    public void ConfigureServices(IServiceCollection services)
    {
        services.TryAddSingleton<IClientErrorFactory, ProblemDetailsErrorFactory>();
    
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }
    
  4. 控制器操作

    [ApiController]
    public class PostController : Controller
    {
        [HttpGet("posts")]
        public IActionResult Get()
        {
            return new MyBadRequestObjectResult();
        }
        [HttpGet("posts1")]
        public IActionResult Get1()
        {
            List<String> errors = new List<String> { "Code is invalid" };
            return new MyBadRequestObjectResult(errors);
        }
    }
    

答案 2 :(得分:0)

尝试使用JsonConvert序列化您的错误请求。

返回BadRequest(JsonConvert.Serialize(新列表{“代码无效”}));

答案 3 :(得分:0)

您无需返回BadRequest()结果,而只需返回ValidationProblem()结果。这将为您提供ProblemDetails对象响应,并填充当前的ModelState错误。