dotnet / dotnet/aspnetcore

ActionResult OK returns 204 on an empty payload instead of 200

Open
#55,835 2 comments 10 reactions 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 5h
Merged PRs (30d)
276

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

This bug has been reported before in #8847 but was unceremoniously closed as working by design, all the while everyone in the thread (including @brunolins16 who closed the bug) has said that it is confusing and bad. I would more state that it is still a bug and should be fixed. (also why is the issue closed to discussion? Nobody was getting rowdy or rude...)

The fact is that when I say I want to return `ActionResult` of `Ok()` that is a **specific** status code and it is what should be returned. There is a specific method to return `NoContent`. So basically the API is not honoring what the developer has requested.

### workaround...
```
services.AddMvc(options =>
{
var noContentFormatter = options.OutputFormatters.OfType().FirstOrDefault();
if (noContentFormatter != null)
{
noContentFormatter.TreatNullValueAsNoContent = false;
}
});
```

Yes there is a way to switch it off - but it's a global change and it means every single method needs to be re-tested to make sure the right status code is being returned - and it's the most important and used status code of all.

So my proposal is, change the default setting of `HttpNoContentOutputFormatter.TreatNullValueAsNoContent` to `false` and make it opt-in instead of opt-out. This was a bad default and should be fixed.

### Documentation

I must also add that the [xml documentation](https://source.dot.net/#Microsoft.AspNetCore.Http.Results/Ok.cs,26) of `Ok()` says "Gets the HTTP status code: Status200OK" so the documentation is wrong too.

### Expected Behavior

Expected behavior is for the status code asked for to be returned. If I want Ok() it should return 200, if NoContent() then 204.

### Steps To Reproduce

Return `Ok(null)` from a controller method which returns 'ActionResult`

### Exceptions (if any)

_No response_

### .NET Version

8

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.