-
Notifications
You must be signed in to change notification settings - Fork 10.6k
SupplyParameterFromSession support for Blazor #65184
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dariatiurina
wants to merge
14
commits into
dotnet:main
Choose a base branch
from
dariatiurina:64422-session-data
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 8 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
239b61b
Create SupplyParameterFromSessionAttribute and connected infrastructure
dariatiurina 596df7f
E2E Tests
dariatiurina 1ed92f9
Merge branch 'main' into 64422-session-data
dariatiurina 215c5a7
Added serialization, deserialization to the SessionValueMapper
dariatiurina 89422d9
Check for callback
dariatiurina b47e153
Fixes callbacks and added new tests
dariatiurina ba0c74a
Merge branch 'main' into 64422-session-data
dariatiurina 3ee272d
Small fixes
dariatiurina 5f9ca60
Fixes
dariatiurina 725040a
Fix
dariatiurina ed0b04d
Fix namespaces
dariatiurina ea2bc22
Merge branch 'main' into 64422-session-data
dariatiurina 420c545
Refactor SupplyParameterFromSession to use CascadingParameterSubscrip…
dariatiurina e5692c6
Clean-up
dariatiurina File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
20 changes: 20 additions & 0 deletions
20
src/Components/Components/src/SupplyParameterFromSessionAttribute.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| namespace Microsoft.AspNetCore.Components; | ||
|
|
||
| /// <summary> | ||
| /// Indicates that the value of the associated property should be supplied from | ||
| /// the session with the specified name. | ||
| /// </summary> | ||
| [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] | ||
| public sealed class SupplyParameterFromSessionAttribute : CascadingParameterAttributeBase | ||
| { | ||
| /// <summary> | ||
| /// Gets or sets the name of the session attribute. If not specified, the property name will be used. | ||
|
dariatiurina marked this conversation as resolved.
Outdated
|
||
| /// </summary> | ||
| public string? Name { get; set; } | ||
|
|
||
| /// <inheritdoc /> | ||
| internal override bool SingleDelivery => false; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
26 changes: 26 additions & 0 deletions
26
src/Components/Endpoints/src/Session/ISessionValueMapper.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| namespace Microsoft.AspNetCore.Components.Endpoints; | ||
|
|
||
| /// <summary> | ||
| /// Maps session data values to a model. | ||
| /// </summary> | ||
| public interface ISessionValueMapper | ||
| { | ||
| /// <summary> | ||
| /// Returns the session value with the specified name, deserialized to the specified type. | ||
| /// </summary> | ||
| object? GetValue(string sessionKey, Type targetType); | ||
|
|
||
| /// <summary> | ||
| /// Registers a callback to retrieve the current value of a session property. | ||
| /// The callback will be invoked when the response starts to persist the value. | ||
| /// </summary> | ||
| void RegisterValueCallback(string sessionKey, Func<object?> valueGetter); | ||
|
|
||
| /// <summary> | ||
| /// Unregisters a previously registered callback for the specified session key. | ||
| /// </summary> | ||
| void DeleteValueCallback(string sessionKey); | ||
| } |
115 changes: 115 additions & 0 deletions
115
src/Components/Endpoints/src/Session/SessionValueMapper.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Text.Json; | ||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.AspNetCore.Http.Features; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Microsoft.AspNetCore.Components.Endpoints; | ||
|
|
||
| internal partial class SessionValueMapper : ISessionValueMapper | ||
| { | ||
| private static readonly JsonSerializerOptions _jsonOptions = new(JsonSerializerDefaults.Web); | ||
| private HttpContext? _httpContext; | ||
| private readonly Dictionary<string, List<Func<object?>>> _valueCallbacks = new(); | ||
|
dariatiurina marked this conversation as resolved.
Outdated
|
||
| private readonly ILogger<SessionValueMapper> _logger; | ||
|
|
||
| public SessionValueMapper(ILogger<SessionValueMapper> logger) | ||
| { | ||
| _logger = logger; | ||
| } | ||
|
|
||
| internal void SetRequestContext(HttpContext httpContext) | ||
| { | ||
| _httpContext = httpContext; | ||
| _httpContext.Response.OnStarting(PersistAllValues); | ||
| } | ||
|
|
||
| public object? GetValue(string sessionKey, Type type) | ||
| { | ||
| var session = _httpContext?.Features.Get<ISessionFeature>()?.Session; | ||
| if (session is null) | ||
| { | ||
| return null; | ||
| } | ||
| try | ||
| { | ||
| var json = session.GetString(sessionKey); | ||
|
dariatiurina marked this conversation as resolved.
Outdated
|
||
| if (string.IsNullOrEmpty(json)) | ||
| { | ||
| return null; | ||
| } | ||
| return JsonSerializer.Deserialize(json, type, _jsonOptions); | ||
| } | ||
| catch (JsonException ex) | ||
| { | ||
| Log.SessionDeserializeFail(_logger, ex); | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| public void RegisterValueCallback(string sessionKey, Func<object?> valueGetter) | ||
| { | ||
| if (!_valueCallbacks.TryGetValue(sessionKey, out var callbacks)) | ||
| { | ||
| callbacks = new List<Func<object?>>(); | ||
| _valueCallbacks[sessionKey] = callbacks; | ||
| } | ||
| callbacks.Add(valueGetter); | ||
| } | ||
|
|
||
| public void DeleteValueCallback(string sessionKey) | ||
| { | ||
| _valueCallbacks.Remove(sessionKey); | ||
| } | ||
|
|
||
| private Task PersistAllValues() | ||
| { | ||
| var session = _httpContext?.Features.Get<ISessionFeature>()?.Session; | ||
| if (session is null) | ||
| { | ||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| foreach (var (key, callbacks) in _valueCallbacks) | ||
| { | ||
| object? value = null; | ||
| foreach (var valueGetter in callbacks) | ||
| { | ||
| try | ||
| { | ||
| var candidateValue = valueGetter(); | ||
| if (candidateValue is not null) | ||
| { | ||
| value = candidateValue; | ||
| break; | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| Log.SessionPersistFail(_logger, ex); | ||
| } | ||
| } | ||
| if (value is not null) | ||
| { | ||
| var json = JsonSerializer.Serialize(value, value.GetType(), _jsonOptions); | ||
| session.SetString(key, json); | ||
|
dariatiurina marked this conversation as resolved.
Outdated
|
||
| } | ||
| else | ||
| { | ||
| session.Remove(key); | ||
|
dariatiurina marked this conversation as resolved.
Outdated
|
||
| } | ||
| } | ||
| return Task.CompletedTask; | ||
| } | ||
|
|
||
| private static partial class Log | ||
| { | ||
| [LoggerMessage(1, LogLevel.Warning, "Persisting of the element failed.", EventName = "SessionPersistFail")] | ||
| public static partial void SessionPersistFail(ILogger logger, Exception exception); | ||
|
|
||
| [LoggerMessage(2, LogLevel.Warning, "Deserialization of the element from Session failed.", EventName = "SessionDeserializeFail")] | ||
| public static partial void SessionDeserializeFail(ILogger logger, JsonException exception); | ||
| } | ||
| } | ||
23 changes: 23 additions & 0 deletions
23
...Components/Endpoints/src/Session/SupplyParameterFromSessionServiceCollectionExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.DependencyInjection.Extensions; | ||
| namespace Microsoft.AspNetCore.Components.Endpoints; | ||
|
|
||
| /// <summary> | ||
| /// Enables component parameters to be supplied from the session with <see cref="SupplyParameterFromSessionAttribute"/>. | ||
| /// </summary> | ||
| public static class SupplyParameterFromSessionServiceCollectionExtensions | ||
| { | ||
| /// <summary> | ||
| /// Enables component parameters to be supplied from the session with <see cref="SupplyParameterFromSessionAttribute"/>. | ||
| /// </summary> | ||
| /// <param name="services">The <see cref="IServiceCollection"/>.</param> | ||
| /// <returns>The <see cref="IServiceCollection"/>.</returns> | ||
| public static IServiceCollection AddSupplyValueFromSessionProvider(this IServiceCollection services) | ||
| { | ||
| services.TryAddEnumerable(ServiceDescriptor.Scoped<ICascadingValueSupplier, SupplyParameterFromSessionValueProvider>()); | ||
| return services; | ||
| } | ||
| } |
64 changes: 64 additions & 0 deletions
64
src/Components/Endpoints/src/Session/SupplyParameterFromSessionValueProvider.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Diagnostics.CodeAnalysis; | ||
| using Microsoft.AspNetCore.Components.Reflection; | ||
| using Microsoft.AspNetCore.Components.Rendering; | ||
|
|
||
| namespace Microsoft.AspNetCore.Components.Endpoints; | ||
|
|
||
| internal class SupplyParameterFromSessionValueProvider : ICascadingValueSupplier | ||
| { | ||
| private readonly ISessionValueMapper _sessionValueMapper; | ||
|
|
||
| public SupplyParameterFromSessionValueProvider(ISessionValueMapper sessionValueMapper) | ||
| { | ||
| _sessionValueMapper = sessionValueMapper; | ||
| } | ||
|
|
||
| public bool IsFixed => false; | ||
|
|
||
| public bool CanSupplyValue(in CascadingParameterInfo parameterInfo) | ||
| => parameterInfo.Attribute is SupplyParameterFromSessionAttribute; | ||
|
|
||
| public object? GetCurrentValue(object? key, in CascadingParameterInfo parameterInfo) | ||
| { | ||
| if (_sessionValueMapper is null) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
|
dariatiurina marked this conversation as resolved.
Outdated
|
||
| var attribute = (SupplyParameterFromSessionAttribute)parameterInfo.Attribute; | ||
| var sessionKey = (attribute.Name ?? parameterInfo.PropertyName) ?? ""; | ||
| return _sessionValueMapper.GetValue(sessionKey, parameterInfo.PropertyType); | ||
| } | ||
|
|
||
| [UnconditionalSuppressMessage( | ||
| "Trimming", | ||
| "IL2075:Target parameter argument does not satisfy 'DynamicallyAccessedMembersAttribute'", | ||
| Justification = "Component properties are preserved through other means.")] | ||
| public void Subscribe(ComponentState subscriber, in CascadingParameterInfo parameterInfo) | ||
| { | ||
| var attribute = (SupplyParameterFromSessionAttribute)parameterInfo.Attribute; | ||
| var sessionKey = (attribute.Name ?? parameterInfo.PropertyName) ?? ""; | ||
| var propertyName = parameterInfo.PropertyName; | ||
| var componentType = subscriber.Component.GetType(); | ||
| var propertyInfo = componentType.GetProperty(propertyName); | ||
|
|
||
| if (propertyInfo is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| var component = subscriber.Component; | ||
| var getter = new PropertyGetter(componentType, propertyInfo); | ||
| _sessionValueMapper.RegisterValueCallback(sessionKey, () => getter.GetValue(component)); | ||
| } | ||
|
|
||
| public void Unsubscribe(ComponentState subscriber, in CascadingParameterInfo parameterInfo) | ||
| { | ||
| var attribute = (SupplyParameterFromSessionAttribute)parameterInfo.Attribute; | ||
| var sessionKey = (attribute.Name ?? parameterInfo.PropertyName) ?? ""; | ||
| _sessionValueMapper.DeleteValueCallback(sessionKey); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.