问题
So OK(value) returns formatted json with an application/json header. However the BadRequest() does not. If the request is a application/json shouldn't the response be like that even if it's a bad request?
[HttpPost]
public IActionResult Post([FromBody]Resolution value)
{
using (_ctx)
{
try
{
if (ValidateResolution(value.Size))
{
_ctx.Resolution.Add(value);
_ctx.SaveChanges();
return Ok(value);
}
return BadRequest("{ \"message\": \"hello\" }");
} catch (Exception) {
return BadRequest();
}
}
}
回答1:
What you're doing is passing a string to BadRequest() which makes your Action return a response with a content-type of plain text.
If you'd like to return a JSON object with a response type of application/json, then you should pass an object that isn't a string to BadRequest(). You can even pass an anonymous object to quickly create a JSON object like so:
return BadRequest(new { message = "bad request"});
PS: The proper JSON format is {"field_name" : "field_value"} (no quotation marks for value is it's a number, bool, null). So from what you've written, even if you changed the content-type to application/json, it could not be properly parsed.
来源:https://stackoverflow.com/questions/44291834/return-json-on-a-bad-request