dotnet / dotnet/aspnetcore

NullReferenceException in Response.CompleteAsync() for 204 No Content response

Open
#62,985 2 comments 0 reactions 0 assignees View on GitHub
area-minimal Needs: Attention :wave:
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

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.