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?
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});
}
You can simply use Controller
class method Json(object data)
.
public IActionResult Foo() {
return Json(new { Hello = "Hi", OneMoreField = 1234});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With