Asp.net core 如何从控制器返回JSON null

Asp.net core 如何从控制器返回JSON null,asp.net-core,Asp.net Core,我有以下行动: [Route("GetNull")] [HttpGet] public IActionResult GetNull() { object value = new { Name = "John" }; return Ok(value); } 它返回序列化对象: HTTP/1.1 200 OK Date: Tue, 12 Jun 2018 06:13:05 GMT Content-Type: applicati

我有以下行动:

    [Route("GetNull")]
    [HttpGet]
    public IActionResult GetNull()
    {
        object value = new { Name = "John" };
        return Ok(value);
    }
它返回序列化对象:

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"
}
如果对象设置为空,如下所示:

    [Route("GetNull")]
    [HttpGet]
    public IActionResult GetNull()
    {
        object value = null;
        return Ok(value);
    }
HTTP/1.1 204 No Content
Date: Tue, 12 Jun 2018 06:17:37 GMT
Server: Kestrel
Content-Length: 0
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Kestrel
Date: Tue, 12 Jun 2018 12:36:33 GMT
我希望JSON中返回null。但是,我得到的是这样的空内容:

    [Route("GetNull")]
    [HttpGet]
    public IActionResult GetNull()
    {
        object value = null;
        return Ok(value);
    }
HTTP/1.1 204 No Content
Date: Tue, 12 Jun 2018 06:17:37 GMT
Server: Kestrel
Content-Length: 0
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Kestrel
Date: Tue, 12 Jun 2018 12:36:33 GMT
我需要让控制器将null序列化为json并返回:

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

ASP.NET Core有一个特定的输出格式化程序,当您尝试返回null时,它将返回
204-NoContent
响应。要允许您返回null并获得200响应,您可以删除NoContent的默认格式化程序

startup.cs
中:

services.AddMvc(options =>
{
    options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
});
您必须注意,ASP.NET将始终尝试将响应格式化为JSON,因为这是默认的响应格式。因此,响应头将如下所示:

    [Route("GetNull")]
    [HttpGet]
    public IActionResult GetNull()
    {
        object value = null;
        return Ok(value);
    }
HTTP/1.1 204 No Content
Date: Tue, 12 Jun 2018 06:17:37 GMT
Server: Kestrel
Content-Length: 0
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Server: Kestrel
Date: Tue, 12 Jun 2018 12:36:33 GMT
重要的是状态代码现在是
200


Microsoft文档是

为什么希望此
返回Json(null)
返回Json(值??“null”)<代码>返回Json(空)