NullReferenceException in Response.CompleteAsync() for 204 No Content response
- 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
When returning a 204 No Content response and calling await HttpContext.Response.CompleteAsync(), a NullReferenceException is thrown due to _writeBodyTask being null.
Awaiting this null , as part of "await HttpContext.Response.CompleteAsync() ", causes exception "System.NullReferenceException: Object reference not set to an instance of an object."
The following code is dereferenced of completeasync and returned _writeBodyTask is null in case of 204 no content response.
```
Task IHttpResponseBodyFeature.CompleteAsync()
{
if (ResponsePipeWrapper != null)
{
var completeAsyncValueTask = ResponsePipeWrapper.CompleteAsync();
if (!completeAsyncValueTask.IsCompletedSuccessfully)
{
return CompleteResponseBodyAwaited(completeAsyncValueTask);
}
completeAsyncValueTask.GetAwaiter().GetResult();
}
if (!HasResponseStarted)
{
var initializeTask = InitializeResponse(flushHeaders: false);
if (!initializeTask.IsCompletedSuccessfully)
{
return CompleteInitializeResponseAwaited(initializeTask);
}
}
// Completing the body output will trigger a final flush to IIS.
// We'd rather not bypass the bodyoutput to flush, to guarantee we avoid
// calling flush twice at the same time.
// awaiting the writeBodyTask guarantees the response has finished the final flush.
_bodyOutput.Complete();
return _writeBodyTask!;
}
```
### Expected Behavior
CompleteAsync() should complete gracefully even when no response body is written (e.g., for 204 responses). A null task should not be awaited or dereferenced. May end with Task.CompletedTask.
### Steps To Reproduce
app.Run(async context =>
{
context.Response.StatusCode = 204;
await context.Response.CompleteAsync(); // Throws NullReferenceException
});
### Exceptions (if any)
_No response_
### .NET Version
_No response_
### Anything else?
_No response_
Contributor guide
Assessment
This issue has not been assessed yet.