Skip to content

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

@adroit18

Description

@adroit18

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs: Attention 👋This issue needs the attention of a contributor, typically because the OP has provided an update.area-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etc

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions