Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OK response helper returns extra json data to response

Tags:

How do I configure ASP.NET Core to not append/add any data to my JSON responses? At the moment it is configured with services.AddMvc(); in ConfigureServices but no custom formatters have been added beyond this.

If I return from my controller method using Ok() (or one of the other help methods like BadRequest, NotFound, Unauthorized..) I get the following response.

Code:

[HttpGet("foo")]
public IActionResult Foo() 
{
    return Ok(Json(new { Hello = "Hi", OneMoreField = 1234}));
}

Response from hitting http://localhost:port/foo

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Date: Mon, 21 Aug 2017 12:14:11 GMT
Server: Kestrel
Transfer-Encoding: chunked

{
    "contentType": null,
    "serializerSettings": null,
    "statusCode": null,
    "value": {
        "hello": "Hi",
        "oneMoreField": 1234
    }
}

If I remove the Ok(...) call and just return Json(new { Hello = "Hi", OneMoreField = 1234}) I get what I expect, an object like this

"value": {
    "hello": "Hi",
    "oneMoreField": 1234
}

What am I missing, is the a debug flag or something I have not toggled correctly?

like image 382
Giffesnaffen Avatar asked Aug 21 '17 12:08

Giffesnaffen


2 Answers

You are not missing anything, but you are certainly doing extra work. The Json helper function is the same as using Ok but forcing the response to be in JSON format. When you do Ok(Json(data)) you are serializing the JsonResult rather than data.

So, use either:

[HttpGet("foo")]
public IActionResult Foo() 
{
    return Json(new { Hello = "Hi", OneMoreField = 1234});
}

Or:

[HttpGet("foo")]
public IActionResult Foo() 
{
    return Ok(new { Hello = "Hi", OneMoreField = 1234});
}
like image 64
Camilo Terevinto Avatar answered Oct 01 '22 03:10

Camilo Terevinto


You can simply use Controller class method Json(object data).

public IActionResult Foo() {
     return Json(new { Hello = "Hi", OneMoreField = 1234});
}
like image 23
Rui Fernandes Avatar answered Oct 01 '22 01:10

Rui Fernandes