Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
7c557e2
Basic E2E test
dariatiurina Dec 10, 2025
8f21417
First simple implementation that holds values no matter what
dariatiurina Dec 10, 2025
43608b0
Made TempData connected to the HttpContext and improved TempData
dariatiurina Dec 11, 2025
5612308
Fixed E2E test to be SSR
dariatiurina Dec 11, 2025
c73f370
Add for manual testing
dariatiurina Dec 11, 2025
9948bcd
Added new E2E tests
dariatiurina Dec 12, 2025
edb2244
Merge branch 'main' into 49683-tempdata
dariatiurina Dec 12, 2025
a9385a6
Merge branch '49683-tempdata' of https://github.com/dariatiurina/aspn…
dariatiurina Dec 12, 2025
9869aa7
Added XML comment
dariatiurina Dec 12, 2025
d93d266
Added new tests
dariatiurina Dec 15, 2025
7630764
Added inheritance from IDictionary
dariatiurina Dec 15, 2025
8b5bbe2
Added IDataProtector to TempDataService
dariatiurina Dec 15, 2025
1d2fc6d
Fix + Enumerator
dariatiurina Dec 15, 2025
31ead26
Fix + unit tests
dariatiurina Dec 15, 2025
68f401d
Merge branch 'main' into 49683-tempdata
dariatiurina Dec 15, 2025
21a3c3b
Fix
dariatiurina Dec 16, 2025
7b50676
TempDataTest
dariatiurina Dec 16, 2025
ecebef8
Fix
dariatiurina Dec 16, 2025
6002ab1
Clean-up
dariatiurina Dec 16, 2025
902cdc9
Add limit for encoded value
dariatiurina Dec 16, 2025
eff02b6
Small decoupling
dariatiurina Dec 17, 2025
1f23e69
Moved to Endpoints
dariatiurina Dec 18, 2025
98ece70
Lazy loading
dariatiurina Dec 18, 2025
bfcace9
Added ITempDataProvider and CookieTempDataProvider
dariatiurina Dec 23, 2025
e5e26c6
Fixed visibility modifiers for TempData and CookieTempDataProvider
dariatiurina Dec 23, 2025
5817356
Decoupling and small fix
dariatiurina Dec 23, 2025
677c014
Update serializer
dariatiurina Dec 23, 2025
c5b0365
Fixes
dariatiurina Dec 23, 2025
8f91662
Fix
dariatiurina Dec 23, 2025
968a345
Fixed lazy loading in TempData
dariatiurina Dec 29, 2025
fab6474
Added options to the ServiceExtensions for Cookie TempData
dariatiurina Dec 29, 2025
0e36b05
Added CookieChunkingManager
dariatiurina Dec 29, 2025
5789c74
Clean-up
dariatiurina Dec 30, 2025
90d1a91
Fix serializer
dariatiurina Dec 30, 2025
03fbc76
Added SessionStorageTempDataProvider
dariatiurina Jan 2, 2026
082a035
Minor fixes
dariatiurina Jan 2, 2026
10fd4d9
Feedback
dariatiurina Jan 12, 2026
077baae
Some small improvements
dariatiurina Jan 12, 2026
12a538d
Changed options
dariatiurina Jan 14, 2026
533f1d4
Made ITempDataProvider internal
dariatiurina Jan 15, 2026
77aa240
Made loadFunc non nullable in the constructor
dariatiurina Jan 15, 2026
90310c4
fix
dariatiurina Jan 15, 2026
4ecd5ed
Changed JsonTempDataSerializer
dariatiurina Jan 16, 2026
c95e54c
fix
dariatiurina Jan 16, 2026
fb958f8
Change naming for test component
dariatiurina Jan 19, 2026
e5bc396
Changed AddTempData
dariatiurina Jan 19, 2026
eb5a42e
Changed RazorComponentsServiceCollectionExtensions
dariatiurina Jan 19, 2026
dd473d7
Changed to internal
dariatiurina Jan 21, 2026
c0e729b
Feedback
dariatiurina Feb 2, 2026
a0d0dff
Fix
dariatiurina Feb 2, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ public static IRazorComponentsBuilder AddRazorComponents(this IServiceCollection
services.TryAddCascadingValue(sp => sp.GetRequiredService<EndpointHtmlRenderer>().HttpContext);
services.TryAddScoped<WebAssemblySettingsEmitter>();
services.TryAddScoped<ResourcePreloadService>();
services.AddTempData();

services.TryAddScoped<ResourceCollectionProvider>();
RegisterPersistentComponentStateServiceCollectionExtensions.AddPersistentServiceRegistration<ResourceCollectionProvider>(services, RenderMode.InteractiveWebAssembly);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using Microsoft.AspNetCore.Components.Endpoints.FormMapping;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Components.Endpoints;

Expand Down Expand Up @@ -83,5 +84,23 @@ public TimeSpan TemporaryRedirectionUrlValidityDuration
}
}

/// <summary>
/// Determines the settings used to create the TempData cookie.
/// </summary>
public CookieBuilder TempDataCookie { get; set; } = new()
{
Name = CookieTempDataProvider.CookieName,
HttpOnly = true,
SameSite = SameSiteMode.Lax,
IsEssential = false,
SecurePolicy = CookieSecurePolicy.SameAsRequest,
};

internal string? JavaScriptInitializers { get; set; }

/// <summary>
/// Gets or sets the storage provider type for TempData.
/// Defaults to <see cref="TempDataProviderType.Cookie"/>.
/// </summary>
public TempDataProviderType TempDataProviderType { get; set; } = TempDataProviderType.Cookie;
}
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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@
<Compile Include="$(ComponentsSharedSourceRoot)src\CacheHeaderSettings.cs" Link="Shared\CacheHeaderSettings.cs" />
<Compile Include="$(ComponentsSharedSourceRoot)src\ResourceCollectionProvider.cs" Link="Shared\ResourceCollectionProvider.cs" />
<Compile Include="$(ComponentsSharedSourceRoot)src\DefaultAntiforgeryStateProvider.cs" LinkBase="Forms" />
<Compile Include="$(SharedSourceRoot)Buffers\RefPooledArrayBufferWriter.cs" Link="Shared\Buffers\%(Filename)%(Extension)" />
<Compile Include="$(SharedSourceRoot)LinkerFlags.cs" LinkBase="Shared" />
<Compile Include="$(SharedSourceRoot)ChunkingCookieManager\**\*.cs" LinkBase="Internal" />
Comment thread
ilonatommy marked this conversation as resolved.
Resolved
<Compile Include="$(SharedSourceRoot)Components\ComponentsActivityLinkStore.cs" LinkBase="Shared" />
<Compile Include="$(ComponentsSharedSourceRoot)src\HotReloadManager.cs" LinkBase="HotReload" />

Expand Down
12 changes: 12 additions & 0 deletions src/Components/Endpoints/src/PublicAPI.Unshipped.txt
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 src/Components/Endpoints/src/TempData/CookieTempDataProvider.cs
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;
}
}
}
Comment thread
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);
}
}
32 changes: 32 additions & 0 deletions src/Components/Endpoints/src/TempData/ITempData.cs
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 src/Components/Endpoints/src/TempData/ITempDataSerializer.cs
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);
}
Loading
Loading