ControllerBase.Ok(object value) responds with 204 status code when value is null #8847
Describe the bug
Returning Ok(null) from a controller action results in a 204 status code, rather than a 200. I'm not sure if this in intended, but it's not what I would expect.
To Reproduce
Steps to reproduce the behavior:
Using this version of ASP.NET Core '2.2'
Create a controller with the following method:
[HttpGet]
public async Task<IActionResult> Test(bool x)
{
if (x)
{
return Ok(null);
}
else
{
return Ok(new { });
}
}
Make a HTTP Get request to the endpoint where x in the query string is true. The response status code will be 204.
Make a HTTP Get request to the endpoint where x in the query string is false. The response status code will be 200 as expected.
Expected behavior
Response status code should always be 200 when returning Ok()
or Ok(object value)
, regardless of if value is null.
This behaviour is done by Microsoft.AspNetCore.Mvc.Formatters.HttpNoContentOutputFormatter, the default configuration of this formatter will return 204 NO CONTENT if the body is null. To opt-out add this configuration in your Startup.ConfigureServices method:
services.AddMvc(options =>
{
var noContentFormatter = options.OutputFormatters.OfType<HttpNoContentOutputFormatter>().FirstOrDefault();
if (noContentFormatter != null)
{
noContentFormatter.TreatNullValueAsNoContent = false;
}
});
The behaviour is indeed confusing.