Skip to content

[release/11.0-preview5] SupplyParameterFromSession support for Blazor - #66756

Merged
wtgodbe merged 1 commit into
dotnet:release/11.0-preview5from
dariatiurina:backport-65184top5
May 20, 2026
Merged

wtgodbe merged 1 commit into
dotnet:release/11.0-preview5from
dariatiurina:backport-65184top5

Conversation

@dariatiurina

Copy link
Copy Markdown
Contributor

Backport of #66528 to release/11.0-preview5

SupplyParameterFromSession support for Blazor

Summary

Adds a new [SupplyParameterFromSession] attribute that allows Blazor SSR components to declaratively read and write HTTP session data, following the same pattern as [SupplyParameterFromQuery] and [SupplyParameterFromForm].

Motivation

Currently, Blazor SSR lacks a simple, declarative way to access session data. Developers who want to persist user-specific data across HTTP requests (like shopping cart contents or multi-step form state) must:

  • Inject IHttpContextAccessor and manually interact with ISession
  • Handle serialization/deserialization manually
  • Write boilerplate code for each session value

This creates inconsistent patterns across applications and increases the likelihood of errors.

Changes

  • SupplyParameterFromSessionAttribute (Components.Web) — A new public attribute inheriting from CascadingParameterAttributeBase with an optional Name property to specify the session key (defaults to the property name). SingleDelivery is false, so values are re-supplied on each render.
  • SessionCascadingValueSupplier (Components.Endpoints) — Internal scoped service that:
    • Reads values from ISession via ISessionFeature and deserializes them using System.Text.Json (with JsonSerializerDefaults.Web)
    • Registers a Response.OnStarting callback to persist all tracked property values back to the session before the response is sent
    • Uses case-insensitive session keys (lowercased via ToLowerInvariant())
    • Caches PropertyGetter instances per component type/property pair using a ConcurrentDictionary
    • Logs warnings (without throwing) when serialization or deserialization fails
    • Enforces unique session keys — throws InvalidOperationException if multiple components register the same key
  • SessionSubscription (inner class of SessionCascadingValueSupplier) — On the first GetCurrentValue() call, reads from the session; on subsequent calls, returns the current component property value (enabling two-way binding). Removes the value callback on Dispose.
  • DI registration — AddRazorComponents() now registers SessionCascadingValueSupplier as a scoped service and wires it as a cascading value supplier for SupplyParameterFromSessionAttribute.
  • EndpointHtmlRenderer — Calls SessionCascadingValueSupplier.SetRequestContext(httpContext) during standard service initialization.
  • Public API surface — Added to PublicAPI.Unshipped.txt: SupplyParameterFromSessionAttribute class, its constructor, and Name property.

Usage

Developers must configure session middleware in their application:

builder.Services.AddDistributedMemoryCache();
builder.Services.AddSession(options =>
{
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});

app.UseSession();

Then use the attribute on component properties:

@code {
    [SupplyParameterFromSession]
    public string? Email { get; set; }

    [SupplyParameterFromSession(Name = "user_email")]
    public string? UserEmail { get; set; }

    [SupplyParameterFromSession]
    public ShoppingCart? Cart { get; set; }
}

Values are read from the session on first render and automatically persisted back when the response starts.

Testing

  • Unit tests (SessionCascadingValueSupplierTest) — 10 tests covering: callback registration, duplicate key rejection, value persistence to session, null value removal, multiple keys, exception resilience (both callback and serialization errors), key lowercasing, no-op when session is unavailable, callback deletion, and OnStarting integration.
  • Unit tests (SessionSubscriptionTest) — 8 tests covering: null when HttpContext not set, null for missing keys, value retrieval, key lowercasing, enum deserialization, null on deserialization failure, component-value passthrough on subsequent calls, and full CreateSubscription round-trip.
  • E2E tests (SupplyParameterFromSessionAttributeTest) — 5 Selenium tests covering: reading from session, null for missing keys, redirect persistence, complex type serialization, and cross-navigation persistence.
  • Test infrastructure — Refactored RazorComponentEndpointsNoInteractivityStartup to separate session middleware configuration (--UseSession) from TempData session storage (--UseSessionStorageTempDataProvider), added Microsoft.AspNetCore.Session reference to test server project, and added two test Razor components.

Fixes #64422

Customer Impact

New feature to test in P5.

Regression?

  • Yes
  • No

Risk

  • High
  • Medium
  • Low

New feature, no users will be impacted by changes.

Verification

  • Manual (required)
  • Automated

Packaging changes reviewed?

  • Yes
  • No
  • N/A

When servicing release/2.3

  • Make necessary changes in eng/PatchConfig.props

@github-actions github-actions Bot added the area-blazor Includes: Blazor, Razor Components label May 20, 2026
@dariatiurina
dariatiurina marked this pull request as ready for review May 20, 2026 16:37
@dariatiurina
dariatiurina requested a review from a team as a code owner May 20, 2026 16:37
Copilot AI review requested due to automatic review settings May 20, 2026 16:37

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Backports the new Blazor SSR feature [SupplyParameterFromSession], enabling components to declaratively read/write values from ISession (similar to existing [SupplyParameterFromTempData] patterns) during endpoint rendering, plus adds unit/E2E coverage and test-server plumbing to enable session.

Changes:

  • Introduces SupplyParameterFromSessionAttribute (public API) and registers a new session-based cascading value supplier in AddRazorComponents().
  • Adds SessionCascadingValueSupplier to read initial values from session and persist tracked values on Response.OnStarting.
  • Adds unit tests and E2E test assets/infra updates to validate SSR and interactive-mode behavior.

Reviewed changes

Copilot reviewed 16 out of 16 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/Components/Web/src/SupplyParameterFromSessionAttribute.cs Adds the new public attribute used to opt-in to session-backed parameter supply.
src/Components/Web/src/PublicAPI.Unshipped.txt Declares the new public API surface for the attribute.
src/Components/Endpoints/src/SessionCascadingValueSupplier.cs Implements session read + OnStarting persistence for supplied parameters.
src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.cs Wires HttpContext into the session supplier during SSR initialization.
src/Components/Endpoints/src/DependencyInjection/RazorComponentsServiceCollectionExtensions.cs Registers SessionCascadingValueSupplier and the supplier mapping for the new attribute.
src/Components/Endpoints/test/Session/SessionSubscriptionTest.cs Adds unit tests validating subscription read semantics + persistence integration.
src/Components/Endpoints/test/Session/SessionCascadingValueSupplierTest.cs Adds unit tests validating callback registration, persistence, error handling, and key behavior.
src/Components/test/testassets/Components.TestServer/RazorComponentEndpointsNoInteractivityStartup.cs Updates test-server configuration to optionally enable session middleware/services.
src/Components/test/testassets/Components.TestServer/Components.TestServer.csproj Adds a reference needed for session middleware in the test server.
src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/SupplyParameterFromSessionComponent.razor Adds SSR test page that reads/writes session-backed parameters.
src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/SupplyParameterFromSessionNavigationComponent.razor Adds SSR navigation page to validate persistence across navigation.
src/Components/test/testassets/BasicTestApp/SupplyParameterFromSessionInteractive.razor Adds an interactive-mode component to validate session/tempdata don’t flow there.
src/Components/test/testassets/BasicTestApp/Index.razor Exposes the new interactive test component in the selector list.
src/Components/test/E2ETest/Tests/TempDataSessionStorageTest.cs Ensures session is enabled for TempData session-storage E2E coverage.
src/Components/test/E2ETest/Tests/SupplyParameterFromSessionInteractiveTest.cs Adds interactive-mode E2E coverage for the new attribute (and tempdata).
src/Components/test/E2ETest/Tests/SupplyParameterFromSessionAttributeTest.cs Adds SSR E2E coverage for reading/writing and navigation persistence.

@wtgodbe wtgodbe added the tell-mode Indicates a PR which is being merged during tell-mode label May 20, 2026
@wtgodbe

wtgodbe commented May 20, 2026

Copy link
Copy Markdown
Member

Mac machines are down right now. Change was previously validated against main - merging

@wtgodbe
wtgodbe merged commit 36326dc into dotnet:release/11.0-preview5 May 20, 2026
27 of 34 checks passed
@wtgodbe wtgodbe added this to the 11.0-preview5 milestone May 21, 2026
@dariatiurina
dariatiurina deleted the backport-65184top5 branch September 29, 2026 09:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-blazor Includes: Blazor, Razor Components tell-mode Indicates a PR which is being merged during tell-mode

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants