Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Json on a bad request

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();
        }
    }
}
like image 519
Ryan Knopp Avatar asked May 31 '17 18:05

Ryan Knopp


1 Answers

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"} (quotation marks are not necessary for the value if its type is 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.

like image 167
Omar Beyhum Avatar answered Oct 12 '22 11:10

Omar Beyhum