I am using an ASP.NET Core 2.2 ApiController and I have the following:

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

In this case I get the following response:

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

But if I return some data as follows:

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

I get the following:

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

Why does ApiController adds type, title, status and traceId when no content is returned?

I would like the responses to be always similar like:

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

3 Answers

1
Dai On

The default ControllerBase.BadRequest() response content is because you have the [ApiController] attribute applied to your controller. This is documented online:

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

When the compatibility version is 2.2 or later, MVC transforms an error result (a result with status code 400 or higher) to a result with ProblemDetails. The ProblemDetails type is based on the RFC 7807 specification for providing machine-readable error details in an HTTP response.

This includes the type, title,statusandtraceId` values: https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2#problem-details-for-error-status-codes

If you do not have [ApiController] applied then ControllerBase.BadRequest() will return an empty response with HTTP 400 status code.

All overloads of ControllerBase.BadRequest that accept a value or model response object will serialize and return that instead of using the ApiController default response.

0
Paul On

Try to serialize your bad request using JsonConvert.

return BadRequest(JsonConvert.Serialize(new List { “Code is invalid” }));

1
Tao Zhou On

For ProblemDetails, it depends on whether the ObjectResult inherited from IClientErrorActionResult.

You could follow steps below for a workaround:

  1. MyBadRequestObjectResult

    public class MyBadRequestObjectResult : BadRequestObjectResult, IClientErrorActionResult
    {
        public MyBadRequestObjectResult() : base((object)null)
        {
        }
    
        public MyBadRequestObjectResult(object error) : base(error)
        {
        }
    }
    
  2. Custom 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. Register ProblemDetailsErrorFactory

    public void ConfigureServices(IServiceCollection services)
    {
        services.TryAddSingleton<IClientErrorFactory, ProblemDetailsErrorFactory>();
    
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }
    
  4. Controller Action

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