Skip to content

SupplyParameterFromSession support for Blazor#65184

Open
dariatiurina wants to merge 14 commits intodotnet:mainfrom
dariatiurina:64422-session-data
Open

SupplyParameterFromSession support for Blazor#65184
dariatiurina wants to merge 14 commits intodotnet:mainfrom
dariatiurina:64422-session-data

Conversation

@dariatiurina
Copy link
Copy Markdown
Contributor

@dariatiurina dariatiurina commented Jan 22, 2026

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 registrationAddRazorComponents() 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

@github-actions github-actions Bot added the area-blazor Includes: Blazor, Razor Components label Jan 22, 2026
@dariatiurina dariatiurina self-assigned this Feb 2, 2026
@dariatiurina dariatiurina marked this pull request as ready for review February 3, 2026 14:01
@dariatiurina dariatiurina requested a review from a team as a code owner February 3, 2026 14:01
Copilot AI review requested due to automatic review settings February 9, 2026 16:58
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds [SupplyParameterFromSession] support for Blazor SSR by introducing a session-backed cascading value supplier and request-scoped session value mapper, plus test assets and E2E/unit tests to validate behavior.

Changes:

  • Introduces SupplyParameterFromSessionAttribute, session value provider, and ISessionValueMapper/SessionValueMapper.
  • Wires session value mapper into EndpointHtmlRenderer request initialization and registers services via AddRazorComponents().
  • Adds test server pages and E2E/unit tests for reading/writing session-backed parameters across navigations.

Reviewed changes

Copilot reviewed 18 out of 18 changed files in this pull request and generated 11 comments.

Show a summary per file
File Description
src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/SupplyParameterFromSessionNavigationComponent.razor Adds navigation test page used to validate session persistence across redirects.
src/Components/test/testassets/Components.TestServer/RazorComponents/Pages/SupplyParameterFromSessionComponent.razor Adds SSR test page exercising primitive, named-key, null, and complex session values.
src/Components/test/testassets/Components.TestServer/RazorComponentEndpointsNoInteractivityStartup.cs Adds conditional session service/middleware setup for the tests.
src/Components/test/testassets/Components.TestServer/Components.TestServer.csproj Adds Session assembly reference for the test server.
src/Components/test/E2ETest/Tests/SupplyParameterFromSessionAttributeTest.cs Adds E2E coverage for session parameter read/write and navigation persistence.
src/Components/Endpoints/test/SessionValueMapperTest.cs Adds unit tests for SessionValueMapper serialization, persistence, and error handling.
src/Components/Endpoints/src/Session/SupplyParameterFromSessionValueProvider.cs Implements the cascading value supplier that binds component properties to session keys.
src/Components/Endpoints/src/Session/SupplyParameterFromSessionServiceCollectionExtensions.cs Adds DI extension to register the session value supplier.
src/Components/Endpoints/src/Session/SessionValueMapper.cs Implements session read/write with JSON serialization and response on-start persistence.
src/Components/Endpoints/src/Session/ISessionValueMapper.cs Adds public contract for session value mapping and persistence callbacks.
src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.cs Initializes the session mapper with the current request HttpContext.
src/Components/Endpoints/src/Rendering/EndpointHtmlRenderer.Prerendering.cs Widens accessibility of overrides (likely to enable cross-assembly usage).
src/Components/Endpoints/src/Rendering/EndpointComponentState.cs Widens accessibility of GetComponentKey override.
src/Components/Endpoints/src/PublicAPI.Unshipped.txt Declares newly added public APIs for the Endpoints assembly.
src/Components/Endpoints/src/DependencyInjection/RazorComponentsServiceCollectionExtensions.cs Registers ISessionValueMapper and session value provider in AddRazorComponents().
src/Components/Components/src/SupplyParameterFromSessionAttribute.cs Adds the public attribute for supplying values from session.
src/Components/Components/src/PublicAPI.Unshipped.txt Declares newly added public APIs for the Components assembly.
src/Components/Components/src/Microsoft.AspNetCore.Components.csproj Adds internals visibility to allow Endpoints to consume internal attribute members.

Comment thread src/Components/Endpoints/src/Session/SessionValueMapper.cs Outdated
Comment thread src/Components/Endpoints/src/Session/SessionValueMapper.cs Outdated
Comment thread src/Components/Endpoints/src/Session/SessionValueMapper.cs Outdated
Comment thread src/Components/Endpoints/src/Session/SessionValueMapper.cs Outdated
Comment thread src/Components/Components/src/SupplyParameterFromSessionValueProvider.cs Outdated
Comment thread src/Components/Endpoints/src/Session/SupplyParameterFromSessionValueProvider.cs Outdated
Comment thread src/Components/Components/src/SupplyParameterFromSessionAttribute.cs Outdated
@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Feb 23, 2026
Comment thread src/Components/Components/src/ISessionValueMapper.cs Outdated
Comment thread src/Components/Components/src/PublicAPI.Unshipped.txt Outdated
Comment thread src/Components/Web/src/SupplyParameterFromSessionAttribute.cs
@dariatiurina dariatiurina removed the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Apr 20, 2026
@dariatiurina dariatiurina requested a review from javiercn April 21, 2026 12:48
@dariatiurina dariatiurina added this to the 11.0-preview5 milestone Apr 22, 2026
@dariatiurina dariatiurina requested a review from ilonatommy April 22, 2026 10:13
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Blazor SessionData

3 participants