Return Json on a bad request

自闭症网瘾萝莉.ら 提交于 2020-07-20 10:09:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!