Home > OS >  Change 400 error response returned from the model binder in ASP.NET Web API
Change 400 error response returned from the model binder in ASP.NET Web API

Time:10-26

I have a Web API project created in .NET 6 and a Controller action with the following signature:

[HttpPost("my/route")]
public async Task<IActionResult> Post([FromBody]MyRequest myRequest)

If I post with a JSON payload that cannot be model bound to a MyRequest, then I get the following error message:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-6f50cde5f3c24d3f9ae15432b4878299-dff20b1783488d15-00",
    "errors": {
        "$.UserId": [
            "The JSON value could not be converted to System.Guid. Path: $.UserId | LineNumber: 1 | BytePositionInLine: 16."
        ]
    }
}

How can I customize this response so that I return different JSON attributes and values?

CodePudding user response:

You can customise the responses by creating new API Behaviour for validation failures, See https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-6.0#validation-failure-error-response-1

  • Related