Skip to content

Commit 2fdf882

Browse files
authored
Setting headers after the response starts (#35549)
1 parent ac4a686 commit 2fdf882

2 files changed

Lines changed: 16 additions & 0 deletions

File tree

aspnetcore/blazor/components/httpcontext.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,19 @@ For additional context in *advanced* edge cases†, see the discussion in t
3232

3333
&dagger;Most developers building and maintaining Blazor apps don't need to delve into advanced concepts when the general guidance in this article is followed. The most important concept to keep in mind is that <xref:Microsoft.AspNetCore.Http.HttpContext> is fundamentally a server-based, request-response feature that's only generally available on the server during static SSR and only created when a user's circuit is established.
3434

35+
## Don't set or modify headers after the response starts
36+
37+
Attempting to set or modify a header after the first rendering (after the response starts) results in an error:
38+
39+
> :::no-loc text="System.InvalidOperationException: 'Headers are read-only, response has already started.'":::
40+
41+
Examples of situations that result in this error include:
42+
43+
* Calling <xref:Microsoft.AspNetCore.Identity.SignInManager%601.PasswordSignInAsync%2A?displayProperty=nameWithType>, which must set headers for Identity to function correctly, while adopting [streaming rendering](xref:blazor/components/rendering#streaming-rendering).
44+
* Attempting to set or modify a header after the response has started during interactive rendering.
45+
46+
For guidance on setting headers before the response starts, see <xref:blazor/fundamentals/startup#control-headers-in-c-code>.
47+
3548
:::moniker-end
3649

3750
:::moniker range="< aspnetcore-8.0"

aspnetcore/blazor/fundamentals/startup.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -525,6 +525,9 @@ Control headers at startup in C# code using the following approaches.
525525

526526
In the following examples, a [Content Security Policy (CSP)](https://developer.mozilla.org/docs/Web/HTTP/Guides/CSP) is applied to the app via a CSP header. The `{POLICY STRING}` placeholder is the CSP policy string. For more information on CSPs, see <xref:blazor/security/content-security-policy>.
527527

528+
> [!NOTE]
529+
> Headers can't be set after the response starts. The approaches in this section only set headers before the response starts, so the approaches described here are safe. For more information, see <xerf:blazor/components/httpcontext#dont-set-or-modify-headers-after-the-response-starts>.
530+
528531
### Server-side and prerendered client-side scenarios
529532

530533
Use [ASP.NET Core Middleware](xref:fundamentals/middleware/index) to control the headers collection.

0 commit comments

Comments
 (0)