Sandy
Sandy

Reputation: 1504

How to return JSON null result from a controller

I have the following action:

    [Route("GetNull")]
    [HttpGet]
    public IActionResult GetNull()
    {
        object value = new { Name = "John" };
        return Ok(value);
    }

It returns the serialized object:

HTTP/1.1 200 OK
Date: Tue, 12 Jun 2018 06:13:05 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Content-Length: 22

{
  "name": "John"
}

If the object is set to null like this:

    [Route("GetNull")]
    [HttpGet]
    public IActionResult GetNull()
    {
        object value = null;
        return Ok(value);
    }

I would expect null in JSON to be returned. However, I get empty content like this:

HTTP/1.1 204 No Content
Date: Tue, 12 Jun 2018 06:17:37 GMT
Server: Kestrel
Content-Length: 0

I do I get the controller to serialize null into json and return:

HTTP/1.1 200 OK
Date: Tue, 12 Jun 2018 06:13:05 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Content-Length: 4

null

Upvotes: 1

Views: 4617

Answers (2)

TidyDev
TidyDev

Reputation: 3668

As documented by Microsoft, you can return a null JsonResult from your controller.

For example,

return Json(null);

However a better approach might be to return an OK status, if that is all you need.

return Ok();

Upvotes: 0

Simply Ged
Simply Ged

Reputation: 8652

ASP.NET Core has a specific output formatter that returns the 204 - NoContent response when you try to return null. To allow you to return null and get a 200 response you can remove the default formatter for NoContent.

In startup.cs:

services.AddMvc(options =>
{
    options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
});

This will allow you to do the following and get a 200 OK response:

[HttpGet]
public IActionResult GetNull()
{
    object value = null;
    return Ok(value);
}

You must note that ASP.NET will always try to format the response as JSON as that is the default response format. So the response header will look like this:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Kestrel
Date: Tue, 12 Jun 2018 12:36:33 GMT

The important thing is the status code is now 200.

The Microsoft documentation is here

Upvotes: 5

Related Questions