dotnet / dotnet/aspnetcore

HttpNoContentOutputFormatter is not working when action is type of Task or void

Open
#58,727 0 comments 1 reaction 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [x] I have searched the existing issues

### Describe the bug

[HttpNoContentOutputFormatter](https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Core/src/Formatters/HttpNoContentOutputFormatter.cs) is designed to override 200 status code to 204 when there is no content (which expected when we have void or Task return types). But in practice having a method with a void return type resulted in 200 status code even though I manually added HttpNoContentOutputFormatter.

### Expected Behavior

HttpNoContentOutputFormatter is working for void and Task actions

### Steps To Reproduce

Problem investigation:
Ensure we have only one output formatter:
```
services.AddControllers(
options =>
{
options.OutputFormatters.Clear();
options.OutputFormatters.Insert(0, new TestHttpNoContentOutputFormatter());
})
```
where TestHttpNoContentOutputFormatter - customer output formatter, but it is a copy of the HttpNoContentOutputFormatter .
Set the break point inside the CanWriteResult method.
Prepare test methods
```
[HttpGet]
[Route("~/test/null_respone")]
[AllowAnonymous]

public object TestTest()
{

return null;
}

[HttpGet]
[Route("~/test/empty_respone")]
[AllowAnonymous]

public void TestTest1()
{

}
```

Make requests:
![Image](https://github.com/user-attachments/assets/2090e0cf-60b3-440d-ab6e-3bac4c70f8e7)

Actually, in debugger, I hit the break point in TestHttpNoContentOutputFormatter only when go to test/null_respone. Seems like the part of the code which responds for IOutputFormatters execution is ignored when you have void and Task return types.

### Exceptions (if any)

_No response_

### .NET Version

8.0.303

### 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.