skip to content

In ASP.NET Core custom middleware, why does setting a response header after await next(context) sometimes throw, and how do Response.HasStarted and Response.OnStarting help?

level: seniorimportance: should knowfreq 40%

answer

  1. headers go out with the first body write
  2. Headers are read-only, response has already started
  3. HasStarted: have headers been sent?
  4. OnStarting: register before calling next
  5. OnCompleted: after the response is sent

basics

~20 s

Once the endpoint writes the body, the headers have been sent and Kestrel throws InvalidOperationException on any header or status change. Check Response.HasStarted before changing them, or register Response.OnStarting before next so the header is set just before it goes out.

solid answer

~40 s

A response **starts** when its status line and headers are sent: on the first body write or flush, an explicit `Response.StartAsync`, or when the pipeline finishes. After that, Kestrel rejects changes: setting a header throws `InvalidOperationException` ("Headers are read-only, response has already started.") and setting `StatusCode` throws too. So middleware that adds `X-Brand` after `await next(context)` works for a 204 that wrote nothing and throws for a JSON body, which is why it looks intermittent. `Response.HasStarted` tells you whether you are still allowed to change status and headers. `Response.OnStarting(callback)`, registered **before** calling `next`, runs the callback just before the headers are sent, whatever the endpoint does; registering it after the response started throws as well. For work after the response is fully sent, use `Response.OnCompleted`.

code

csharp · 22 lines
csharp
public sealed class BrandHeaderMiddleware(RequestDelegate next)
{
    public async Task InvokeAsync(HttpContext context, ITenantContext tenant)
    {
        // Runs just before the headers are sent, whatever the endpoint writes
        context.Response.OnStarting(() =>
        {
            context.Response.Headers["X-Brand"] = tenant.BrandName;
            return Task.CompletedTask;
        });

        await next(context);

        // Too late once the endpoint wrote a body:
        // context.Response.Headers["X-Brand"] = tenant.BrandName;  -> InvalidOperationException

        if (!context.Response.HasStarted && context.Response.StatusCode == StatusCodes.Status404NotFound)
        {
            await context.Response.WriteAsync("No such product for this brand.");
        }
    }
}

go deeper

for a junior

Remember that headers and status code must be set before the body is written, and that HasStarted tells you whether that moment has passed.

for a middle

Explain what starts a response, why the exception depends on whether the endpoint wrote a body, and how OnStarting registered before next solves it.

for a senior

Debug intermittent read-only header exceptions, reason about OnStarting callback order across nested middleware, and choose OnCompleted for post-response work.

for a principal

Agree conventions for cross-cutting response headers, such as OnStarting-based middleware owned by one team, so services do not each reinvent fragile header logic.

## When a response starts An HTTP response is sent in order: status, headers, then body. ASP.NET Core buffers the status code and headers in `HttpResponse` until the response **starts**, which with Kestrel happens when: - the app writes the first bytes of the body, or flushes; - code calls `HttpResponse.StartAsync()` explicitly; - the request pipeline completes, in which case Kestrel sends whatever status and headers are set. From that moment `HttpResponse.HasStarted` is `true` and the status code and headers are frozen. With Kestrel: - setting a header throws `InvalidOperationException` ("Headers are read-only, response has already started."); - setting `StatusCode` throws `InvalidOperationException` ("StatusCode cannot be set because the response has already started."); - calling `OnStarting` throws `InvalidOperationException` ("OnStarting cannot be set because the response has already started."). ## Why it looks intermittent In the multi-brand storefront host, a middleware adds an `X-Brand` header after the endpoint ran: ```csharp await next(context); context.Response.Headers["X-Brand"] = tenant.BrandName; // throws for some requests ``` For an endpoint that returns `204 No Content` or a redirect with no body, nothing has been written when control returns, so the header is accepted. For an endpoint that serialises a product list to JSON, the body was written inside `next`, the headers went out with it, and the assignment throws. Same middleware, different endpoints, different outcome. ## HasStarted: a guard, not a fix `HasStarted` lets middleware decide whether it may still change the response: ```csharp await next(context); if (!context.Response.HasStarted && context.Response.StatusCode == StatusCodes.Status404NotFound) { await context.Response.WriteAsync("No such product for this brand."); } ``` It prevents the exception, but if the goal is "every response carries `X-Brand`", skipping the header when the response has started is not acceptable. That needs `OnStarting`. ## OnStarting: run just before the headers go out `HttpResponse.OnStarting(Func<Task>)` (or the `Func<object, Task>` plus state overload) registers a callback that runs **immediately before** the status and headers are sent, while they can still be changed. Register it **before** calling `next`: 1. The middleware registers the callback. 2. It awaits `next(context)`; somewhere inside, the endpoint writes the body. 3. Just before Kestrel sends the headers, it runs the callback, which sets `X-Brand`. 4. The body follows. Kestrel keeps these callbacks on a stack, so with several registrations the one registered **last** (the innermost middleware) runs first, and the outermost middleware's callback gets the final word on a header both set. Callbacks should be short and must not write to the body; an exception thrown in one is reported as an application error for the request. ## Choosing the right tool | Need | Tool | When to register | |---|---|---| | set a header on every response | `Response.OnStarting` | before `await next(context)` | | set headers or status only when the endpoint wrote nothing | check `Response.HasStarted` | after `await next(context)` | | set a header that does not depend on the endpoint | assign it directly | before `await next(context)` | | run work after the response is sent | `Response.OnCompleted` | any time before the request ends | The simplest fix is often the third row: if `X-Brand` depends only on the tenant, which the middleware already knows, assign it **before** calling `next`. Use `OnStarting` when the value depends on what the endpoint did, such as a header derived from the final status code. ## OnCompleted and RegisterForDispose `HttpResponse.OnCompleted` registers work for **after** the response has been sent, such as recording metrics or releasing a resource. `RegisterForDispose` and `RegisterForDisposeAsync` are built on it. Neither can change the response. ## Writing the body after next The same rule applies to the body. After `next` has written a response with a `Content-Length`, writing more bytes is a protocol violation that Kestrel rejects ("Response Content-Length mismatch: too many bytes written"), and appending text to a non-text response corrupts it. Middleware that needs to transform a body must wrap the body before calling `next`, as the response compression middleware does by swapping in its own `IHttpResponseBodyFeature`.

  • In which order do several OnStarting callbacks run?
    Kestrel stores them on a stack, so they run in reverse registration order: the innermost middleware's callback runs first and the outermost one's runs last. If two callbacks set the same header, the outer middleware's value wins.
  • What would you use for work that must happen after the response is fully sent?
    `HttpResponse.OnCompleted`, which runs after the response has been sent, for example to record metrics. `RegisterForDispose` and `RegisterForDisposeAsync` use it to dispose objects at the end of the request. Neither can change status, headers or body.
  • Can middleware call OnStarting after await next(context) returns?
    Only if the response has not started yet. With Kestrel, registering it after the headers were sent throws `InvalidOperationException` ("OnStarting cannot be set because the response has already started."). Register it before calling `next`.

Response headers are the label on a parcel: once the courier has collected it you cannot change the label, only check whether it has gone (HasStarted). OnStarting is a note left at the counter asking the clerk to add a sticker at the moment the parcel is handed over, so it works however long the packing takes.

  • Headers can be changed any time until the middleware's InvokeAsync returns.
  • HasStarted becomes true as soon as next(context) is called.
  • OnStarting callbacks run after the response body has been sent.
  • Registering OnStarting after the endpoint wrote the body still works.
  • Setting StatusCode is always allowed; only headers become read-only.