We can return ModelState with BadRequest from web api in following way:
return BadRequest(ModelState);
It provides following output:
{
"Message": "The request is invalid.",
"ModelState": {
"property": [
"error"
]
}
}
How can I return the same output with Forbidden status?
I tried following method:
return Content(HttpStatusCode.Forbidden, ModelState);
But it returns:
{
"property": {
"_errors": [
{
"<Exception>k__BackingField": null,
"<ErrorMessage>k__BackingField": "error"
}
],
"<Value>k__BackingField": null
}
}
Json serializing ModelSate is also not returning the same thing. How can I use the serialization method used by BadRequest() method for ModelState with other status codes?
You can achieve the desired output by using the
ExecuteAsyncmethod ofInvalidModelStateResult(return type ofBadRequest()method ofApiController) which actually serializes theModelState.So the idea is to create a new class which extends
InvalidModelStateResultand overrideExecuteAsyncmethod to change the status code.Use it like:
I think this is just a work around, hope someone posts a better way to achieve it.
EDIT:
Without using
InvalidModelStateResult: