what's HttpContext.Response.HasStarted for?

Viewed 1305

For example, ExceptionHandlerMiddleware Middleware code on Github

uses this as:

if (context.Response.HasStarted ||...)

I don't quite get it, how can the web server starts to send response to clients when the request still in the pipeline assuming the ExceptionHandlerMiddleware is the first middleware in the pipeline? Because the request hasn't got out of ExceptionHandlerMiddleware, so it hasn't arrived to the web server, then how could it be that the web server already starts to send responses to client in this scenario?

3 Answers

Any middleware or handler may choose to call WriteAsync (or other similar methods) on the HttpResponse, possibly multiple times.

It's not necessarily possible for all of those writes to just be stored in local buffers, and indeed may not be desirable to just buffer locally. So, sooner or later, those Write calls are going to result in real data being sent over the network.

And, in this concrete example, a handler may have made multiple calls such as the above before it encounters an error condition that causes control to be returned to the ExceptionHandlerMiddleware.

Your specific ExceptionHandlerMiddleware example uses Microsoft.AspNetCore.Http.HttpResponse.HasStarted:

Gets a value indicating whether response headers have been sent to the client.

https://docs.microsoft.com/en-US/dotnet/api/microsoft.aspnetcore.http.httpresponse.hasstarted?view=aspnetcore-5.0


There is also Microsoft.Net.Http.Server.Response.HasStarted:

Indicates if the response status, reason, and headers are prepared to send and can no longer be modified. This is caused by the first write or flush to the response body.

https://docs.microsoft.com/en-US/dotnet/api/microsoft.net.http.server.response.hasstarted?view=aspnetcore-1.1

Each response consis of two parts: Header and Body

These two being sent together to the client, first the headers than the body. So during development, the only opportunity to set any value on the response object that affects the headers is up to the point at which you start sending the body.

As long as you begin sending the body of the response you can no longer change the headers because they are sent as the first part of the response just before the body begins sending.

Related