Reputation: 4217
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"?
Upvotes: 3
Views: 5600
Reputation: 37918
Update: to change default message and keep default formatting for ModelState
errors you can use HttpError
class:
if (!ModelState.IsValid)
{
return Content(HttpStatusCode.BadRequest,
new HttpError(ModelState, includeErrorDetail: true)
{
Message = "Custom mesage"
});
}
Or you can define your own model for validation result and return it with required status code (to rename json field "ModelState"). For example:
class ValdationResult
{
public string Message { get; }
public HttpError Errors { get; }
public ValdationResult(string message, ModelStateDictionary modelState)
{
Message = message;
Errors = new HttpError(modelState, includeErrorDetail: true).ModelState;
}
}
...
if (!ModelState.IsValid)
{
return Content(HttpStatusCode.BadRequest,
new ValdationResult("Custom mesage", ModelState));
}
Upvotes: 1