sahil sahil - 4 months ago 48
ASP.NET (C#) Question

Fluent validation: How to customize the bad request message format?

In my controller, i have put a check:

if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}


This gives me error is specific format, for example:

{
"Message": "The request is invalid.",
"ModelState": {
"stocks.SellerType": [
"SellerType should be greater than 101"
],
"stocks.SourceId": [
"SourceId should be less than 300"
]
}
}


How can i customize this error message format. I know how to customize the error messages i.e. "SourceId should be less than 300". But i have no clue how can i change "Message", remove or rename json field "ModelState"?

Answer

You can define your own model for validation result and return it with required status code. For example:

class ValdationResult
{
    public string Message { get; set; }
    public ModelStateDictionary Errors { get; set; }
}
...

if (!ModelState.IsValid)
{
    return Content(HttpStatusCode.BadRequest, new ValdationResult
    {
        Message = "Custom message",
        Errors = ModelState
    });
}