-
Notifications
You must be signed in to change notification settings - Fork 10.4k
Description
Is there an existing issue for this?
- 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