0

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?

1

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.