简体   繁体   中英

Inconsistent behaviour: Error response object in ASP.NET Core when manually return BadRequest

I have a ASP.NET Core REST Api with both, static and dynamic validation.

When I not specify a required property, the middleware automatically generates a nice error message:

{
    "errors": {
        "status": [
            "Required property 'status' not found in JSON. Path '', line 37, position 1."
        ]
    },
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "|a6b5a076-4b400dadb53f75e7."
}

I also have some kind of dynamic validation where I manually populate the ModelState and return a BadRequest.

Simplified example:

ModelState.AddModelError("smh_data.materials.country_of_origin", "Field is required.");
return BadRequest(ModelState);

But in this case, the response looks like this:

{
    "smh_data.materials.country_of_origin": [
        "Field is required."
    ]
}

How can I get the same response object including traceId, type, title and status like above?

Instead of calling return BadRequest() , call return ValidationProblem() . This will create a ValidationProblemDetails object set to BadRequest , populate it with your ModelState errors, and return it.

Overloads of ValidationProblem() allow for further customisation of the returned response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM