1

I use model validation in Asp.Net Core and it returns 400 errors like that:

{
    "errors": {
        "MyProperty": [
            "Error 1",
            "Error 2"
        ]
    },
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "0HLRTF1TPCO60:00000002"
}

I do have my custom validation that does not use Asp.Net core built-in mechanisms, but I'd like to generate the error in exact same format so that it would be easier for users to consume. I can of course just generate JSON myself, but I think there is some built-in API to generate such an error from model, though I cannot manage to find what should I call.

P.S. I want to do this in middleware

1 Answer 1

3

I have figured out myself how this can be achieved:

var modelState = new ModelStateDictionary();
modelState.AddModelError("FieldName", "ErrorMessage");
var details = new ValidationProblemDetails(modelState);
details.Status = (int?) HttpStatusCode.BadRequest;
details.Extensions["traceId"] = context.TraceIdentifier;

The details can later be serialized to JSON.

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.