Repository navigation
TempData support for Blazor #64749
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
Merged
+2,539
−1
Merged
TempData support for Blazor #64749
Changes from all commits
Commits
Show all changes
50 commits
Select commit
Hold shift + click to select a range
7c557e2
Basic E2E test
dariatiurina 8f21417
First simple implementation that holds values no matter what
dariatiurina 43608b0
Made TempData connected to the HttpContext and improved TempData
dariatiurina 5612308
Fixed E2E test to be SSR
dariatiurina c73f370
Add for manual testing
dariatiurina 9948bcd
Added new E2E tests
dariatiurina edb2244
Merge branch 'main' into 49683-tempdata
dariatiurina a9385a6
Merge branch '49683-tempdata' of https://github.com/dariatiurina/aspn…
dariatiurina 9869aa7
Added XML comment
dariatiurina d93d266
Added new tests
dariatiurina 7630764
Added inheritance from IDictionary
dariatiurina 8b5bbe2
Added IDataProtector to TempDataService
dariatiurina 1d2fc6d
Fix + Enumerator
dariatiurina 31ead26
Fix + unit tests
dariatiurina 68f401d
Merge branch 'main' into 49683-tempdata
dariatiurina 21a3c3b
Fix
dariatiurina 7b50676
TempDataTest
dariatiurina ecebef8
Fix
dariatiurina 6002ab1
Clean-up
dariatiurina 902cdc9
Add limit for encoded value
dariatiurina eff02b6
Small decoupling
dariatiurina 1f23e69
Moved to Endpoints
dariatiurina 98ece70
Lazy loading
dariatiurina bfcace9
Added ITempDataProvider and CookieTempDataProvider
dariatiurina e5e26c6
Fixed visibility modifiers for TempData and CookieTempDataProvider
dariatiurina 5817356
Decoupling and small fix
dariatiurina 677c014
Update serializer
dariatiurina c5b0365
Fixes
dariatiurina 8f91662
Fix
dariatiurina 968a345
Fixed lazy loading in TempData
dariatiurina fab6474
Added options to the ServiceExtensions for Cookie TempData
dariatiurina 0e36b05
Added CookieChunkingManager
dariatiurina 5789c74
Clean-up
dariatiurina 90d1a91
Fix serializer
dariatiurina 03fbc76
Added SessionStorageTempDataProvider
dariatiurina 082a035
Minor fixes
dariatiurina 10fd4d9
Feedback
dariatiurina 077baae
Some small improvements
dariatiurina 12a538d
Changed options
dariatiurina 533f1d4
Made ITempDataProvider internal
dariatiurina 77aa240
Made loadFunc non nullable in the constructor
dariatiurina 90310c4
fix
dariatiurina 4ecd5ed
Changed JsonTempDataSerializer
dariatiurina c95e54c
fix
dariatiurina fb958f8
Change naming for test component
dariatiurina e5bc396
Changed AddTempData
dariatiurina eb5a42e
Changed RazorComponentsServiceCollectionExtensions
dariatiurina dd473d7
Changed to internal
dariatiurina c0e729b
Feedback
dariatiurina a0d0dff
Fix
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
22 changes: 22 additions & 0 deletions
22
src/Components/Endpoints/src/DependencyInjection/ITempDataProvider.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,22 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Microsoft.AspNetCore.Http; | ||
|
|
||
| namespace Microsoft.AspNetCore.Components.Endpoints; | ||
|
|
||
| /// <summary> | ||
| /// Provides an abstraction for a provider that stores and retrieves temporary data. | ||
| /// </summary> | ||
| internal interface ITempDataProvider | ||
| { | ||
| /// <summary> | ||
| /// Loads temporary data from the given <see cref="HttpContext"/>. | ||
| /// </summary> | ||
| IDictionary<string, object?> LoadTempData(HttpContext context); | ||
|
|
||
| /// <summary> | ||
| /// Saves temporary data to the given <see cref="HttpContext"/>. | ||
| /// </summary> | ||
| void SaveTempData(HttpContext context, IDictionary<string, object?> values); | ||
| } |
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
35 changes: 35 additions & 0 deletions
35
src/Components/Endpoints/src/DependencyInjection/TempDataService.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,35 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Microsoft.AspNetCore.Http; | ||
|
|
||
| namespace Microsoft.AspNetCore.Components.Endpoints; | ||
|
|
||
| internal sealed partial class TempDataService | ||
| { | ||
| private readonly ITempDataProvider _tempDataProvider; | ||
|
|
||
| public TempDataService(ITempDataProvider tempDataProvider) | ||
| { | ||
| _tempDataProvider = tempDataProvider; | ||
| } | ||
|
|
||
| public TempData CreateEmpty(HttpContext httpContext) | ||
| { | ||
| return new TempData(() => Load(httpContext)); | ||
| } | ||
|
|
||
| public IDictionary<string, object?> Load(HttpContext httpContext) | ||
| { | ||
| return _tempDataProvider.LoadTempData(httpContext); | ||
| } | ||
|
|
||
| public void Save(HttpContext httpContext, TempData tempData) | ||
| { | ||
| if (!tempData.WasLoaded) | ||
| { | ||
| return; | ||
| } | ||
| _tempDataProvider.SaveTempData(httpContext, tempData.Save()); | ||
| } | ||
| } |
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,15 @@ | ||
| #nullable enable | ||
| Microsoft.AspNetCore.Components.Endpoints.BasePath | ||
| Microsoft.AspNetCore.Components.Endpoints.BasePath.BasePath() -> void | ||
| Microsoft.AspNetCore.Components.Endpoints.RazorComponentsServiceOptions.TempDataCookie.get -> Microsoft.AspNetCore.Http.CookieBuilder! | ||
| Microsoft.AspNetCore.Components.Endpoints.RazorComponentsServiceOptions.TempDataCookie.set -> void | ||
| Microsoft.AspNetCore.Components.Endpoints.RazorComponentsServiceOptions.TempDataProviderType.get -> Microsoft.AspNetCore.Components.Endpoints.TempDataProviderType | ||
| Microsoft.AspNetCore.Components.Endpoints.RazorComponentsServiceOptions.TempDataProviderType.set -> void | ||
| Microsoft.AspNetCore.Components.Endpoints.TempDataProviderType | ||
| Microsoft.AspNetCore.Components.Endpoints.TempDataProviderType.Cookie = 0 -> Microsoft.AspNetCore.Components.Endpoints.TempDataProviderType | ||
| Microsoft.AspNetCore.Components.Endpoints.TempDataProviderType.SessionStorage = 1 -> Microsoft.AspNetCore.Components.Endpoints.TempDataProviderType | ||
| Microsoft.AspNetCore.Components.ITempData | ||
| Microsoft.AspNetCore.Components.ITempData.Get(string! key) -> object? | ||
| Microsoft.AspNetCore.Components.ITempData.Keep() -> void | ||
| Microsoft.AspNetCore.Components.ITempData.Keep(string! key) -> void | ||
| Microsoft.AspNetCore.Components.ITempData.Peek(string! key) -> object? |
169 changes: 169 additions & 0 deletions
169
src/Components/Endpoints/src/TempData/CookieTempDataProvider.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,169 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Buffers; | ||
| using System.Buffers.Text; | ||
| using System.Collections.ObjectModel; | ||
| using System.Text.Json; | ||
| using Microsoft.AspNetCore.DataProtection; | ||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.AspNetCore.Internal; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Extensions.Options; | ||
|
|
||
| namespace Microsoft.AspNetCore.Components.Endpoints; | ||
|
|
||
| internal sealed partial class CookieTempDataProvider : ITempDataProvider | ||
| { | ||
| public const string CookieName = ".AspNetCore.Components.TempData"; | ||
| private const string Purpose = "Microsoft.AspNetCore.Components.CookieTempDataProviderToken"; | ||
| private readonly IDataProtector _dataProtector; | ||
| private readonly ISpanDataProtector? _spanDataProtector; | ||
| private readonly ITempDataSerializer _tempDataSerializer; | ||
| private readonly RazorComponentsServiceOptions _options; | ||
| private readonly ChunkingCookieManager _chunkingCookieManager; | ||
| private readonly ILogger<CookieTempDataProvider> _logger; | ||
|
|
||
| public CookieTempDataProvider( | ||
| IDataProtectionProvider dataProtectionProvider, | ||
| IOptions<RazorComponentsServiceOptions> options, | ||
| ITempDataSerializer tempDataSerializer, | ||
| ILogger<CookieTempDataProvider> logger) | ||
| { | ||
| _dataProtector = dataProtectionProvider.CreateProtector(Purpose); | ||
| _spanDataProtector = _dataProtector as ISpanDataProtector; | ||
| _tempDataSerializer = tempDataSerializer; | ||
| _options = options.Value; | ||
| _chunkingCookieManager = new ChunkingCookieManager(); | ||
| _logger = logger; | ||
| } | ||
|
|
||
| public IDictionary<string, object?> LoadTempData(HttpContext context) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(context); | ||
| var cookieName = _options.TempDataCookie.Name ?? CookieName; | ||
|
|
||
| try | ||
| { | ||
| if (!context.Request.Cookies.ContainsKey(cookieName)) | ||
| { | ||
| Log.TempDataCookieNotFound(_logger, cookieName); | ||
| return ReadOnlyDictionary<string, object?>.Empty; | ||
| } | ||
| var serializedDataFromCookie = _chunkingCookieManager.GetRequestCookie(context, cookieName); | ||
| if (serializedDataFromCookie is null) | ||
| { | ||
| return ReadOnlyDictionary<string, object?>.Empty; | ||
| } | ||
|
|
||
| byte[]? rentedDecodeBuffer = null; | ||
| var maxDecodedSize = Base64Url.GetMaxDecodedLength(serializedDataFromCookie.Length); | ||
| var decodeBuffer = maxDecodedSize <= 256 | ||
| ? stackalloc byte[256] | ||
| : (rentedDecodeBuffer = ArrayPool<byte>.Shared.Rent(maxDecodedSize)); | ||
|
|
||
| try | ||
| { | ||
| var decodeStatus = Base64Url.DecodeFromChars(serializedDataFromCookie, decodeBuffer, out _, out var bytesWritten); | ||
| var protectedBytes = decodeBuffer[..bytesWritten]; | ||
| Dictionary<string, JsonElement>? dataFromCookie; | ||
|
|
||
| if (_spanDataProtector is not null) | ||
| { | ||
| var unprotectBuffer = new RefPooledArrayBufferWriter<byte>(stackalloc byte[256]); | ||
| _spanDataProtector.Unprotect(protectedBytes, ref unprotectBuffer); | ||
| dataFromCookie = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(unprotectBuffer.WrittenSpan); | ||
| } | ||
| else | ||
| { | ||
| var unprotectedBytes = _dataProtector.Unprotect(protectedBytes.ToArray()); | ||
| dataFromCookie = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(unprotectedBytes); | ||
| } | ||
|
|
||
| if (dataFromCookie is null) | ||
| { | ||
| return ReadOnlyDictionary<string, object?>.Empty; | ||
| } | ||
| var convertedData = _tempDataSerializer.DeserializeData(dataFromCookie); | ||
| Log.TempDataCookieLoadSuccess(_logger, cookieName); | ||
| return convertedData; | ||
| } | ||
| finally | ||
| { | ||
| if (rentedDecodeBuffer is not null) | ||
| { | ||
| ArrayPool<byte>.Shared.Return(rentedDecodeBuffer); | ||
| } | ||
| } | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| Log.TempDataCookieLoadFailure(_logger, cookieName, ex); | ||
|
|
||
| var cookieOptions = _options.TempDataCookie.Build(context); | ||
| SetCookiePath(context, cookieOptions); | ||
| context.Response.Cookies.Delete(cookieName, cookieOptions); | ||
| return ReadOnlyDictionary<string, object?>.Empty; | ||
| } | ||
| } | ||
|
|
||
| public void SaveTempData(HttpContext context, IDictionary<string, object?> values) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(context); | ||
|
|
||
| foreach (var kvp in values) | ||
| { | ||
| if (kvp.Value is not null && !_tempDataSerializer.CanSerialize(kvp.Value.GetType())) | ||
| { | ||
| throw new InvalidOperationException($"TempData cannot store values of type '{kvp.Value.GetType()}'."); | ||
| } | ||
| } | ||
|
|
||
| var cookieName = _options.TempDataCookie.Name ?? CookieName; | ||
| var cookieOptions = _options.TempDataCookie.Build(context); | ||
| SetCookiePath(context, cookieOptions); | ||
|
|
||
| if (values.Count == 0) | ||
| { | ||
| _chunkingCookieManager.DeleteCookie(context, cookieName, cookieOptions); | ||
| return; | ||
| } | ||
|
|
||
| var bytes = _tempDataSerializer.SerializeData(values); | ||
| var protectedBytes = _dataProtector.Protect(bytes); | ||
| var encodedValue = Base64Url.EncodeToString(protectedBytes); | ||
| _chunkingCookieManager.AppendResponseCookie(context, cookieName, encodedValue, cookieOptions); | ||
| Log.TempDataCookieSaveSuccess(_logger, cookieName); | ||
| } | ||
|
|
||
| private void SetCookiePath(HttpContext httpContext, CookieOptions cookieOptions) | ||
| { | ||
| if (!string.IsNullOrEmpty(_options.TempDataCookie.Path)) | ||
| { | ||
| cookieOptions.Path = _options.TempDataCookie.Path; | ||
| } | ||
| else | ||
| { | ||
| var pathBase = httpContext.Request.PathBase.ToString(); | ||
| if (!string.IsNullOrEmpty(pathBase)) | ||
| { | ||
| cookieOptions.Path = pathBase; | ||
| } | ||
| } | ||
| } | ||
|
javiercn marked this conversation as resolved.
Resolved
|
||
|
|
||
| private static partial class Log | ||
| { | ||
| [LoggerMessage(1, LogLevel.Debug, "The temp data cookie {CookieName} was not found.", EventName = "TempDataCookieNotFound")] | ||
| public static partial void TempDataCookieNotFound(ILogger logger, string cookieName); | ||
|
|
||
| [LoggerMessage(2, LogLevel.Warning, "The temp data cookie {CookieName} could not be loaded.", EventName = "TempDataCookieLoadFailure")] | ||
| public static partial void TempDataCookieLoadFailure(ILogger logger, string cookieName, Exception exception); | ||
|
|
||
| [LoggerMessage(3, LogLevel.Debug, "The temp data cookie {CookieName} was successfully saved.", EventName = "TempDataCookieSaveSuccess")] | ||
| public static partial void TempDataCookieSaveSuccess(ILogger logger, string cookieName); | ||
|
|
||
| [LoggerMessage(4, LogLevel.Debug, "The temp data cookie {CookieName} was successfully loaded.", EventName = "TempDataCookieLoadSuccess")] | ||
| public static partial void TempDataCookieLoadSuccess(ILogger logger, string cookieName); | ||
| } | ||
| } | ||
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,32 @@ | ||
| // 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> | ||
| /// Provides a dictionary for storing data that is needed for subsequent requests. | ||
| /// Data stored in TempData is automatically removed after it is read unless | ||
| /// <see cref="Keep()"/> or <see cref="Keep(string)"/> is called, or it is accessed via <see cref="Peek(string)"/>. | ||
| /// </summary> | ||
| public interface ITempData : IDictionary<string, object?> | ||
| { | ||
| /// <summary> | ||
| /// Gets the value associated with the specified key and then schedules it for deletion. | ||
| /// </summary> | ||
| object? Get(string key); | ||
|
|
||
| /// <summary> | ||
| /// Gets the value associated with the specified key without scheduling it for deletion. | ||
| /// </summary> | ||
| object? Peek(string key); | ||
|
|
||
| /// <summary> | ||
| /// Makes all of the keys currently in TempData persist for another request. | ||
| /// </summary> | ||
| void Keep(); | ||
|
|
||
| /// <summary> | ||
| /// Makes the element with the <paramref name="key"/> persist for another request. | ||
| /// </summary> | ||
| void Keep(string key); | ||
| } |
15 changes: 15 additions & 0 deletions
15
src/Components/Endpoints/src/TempData/ITempDataSerializer.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,15 @@ | ||
| // 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; | ||
|
|
||
| namespace Microsoft.AspNetCore.Components.Endpoints; | ||
|
|
||
| internal interface ITempDataSerializer | ||
| { | ||
| public IDictionary<string, object?> DeserializeData(IDictionary<string, JsonElement> data); | ||
|
|
||
| public byte[] SerializeData(IDictionary<string, object?> data); | ||
|
|
||
| public bool CanSerialize(Type type); | ||
| } |
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.