Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading