diff --git a/src/Components/Endpoints/src/DependencyInjection/ITempDataProvider.cs b/src/Components/Endpoints/src/DependencyInjection/ITempDataProvider.cs
new file mode 100644
index 000000000000..f87ec34d600e
--- /dev/null
+++ b/src/Components/Endpoints/src/DependencyInjection/ITempDataProvider.cs
@@ -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;
+
+///
+/// Provides an abstraction for a provider that stores and retrieves temporary data.
+///
+internal interface ITempDataProvider
+{
+ ///
+ /// Loads temporary data from the given .
+ ///
+ IDictionary LoadTempData(HttpContext context);
+
+ ///
+ /// Saves temporary data to the given .
+ ///
+ void SaveTempData(HttpContext context, IDictionary values);
+}
diff --git a/src/Components/Endpoints/src/DependencyInjection/RazorComponentsServiceCollectionExtensions.cs b/src/Components/Endpoints/src/DependencyInjection/RazorComponentsServiceCollectionExtensions.cs
index dc365194fcbe..df998d59c72a 100644
--- a/src/Components/Endpoints/src/DependencyInjection/RazorComponentsServiceCollectionExtensions.cs
+++ b/src/Components/Endpoints/src/DependencyInjection/RazorComponentsServiceCollectionExtensions.cs
@@ -74,6 +74,7 @@ public static IRazorComponentsBuilder AddRazorComponents(this IServiceCollection
services.TryAddCascadingValue(sp => sp.GetRequiredService().HttpContext);
services.TryAddScoped();
services.TryAddScoped();
+ services.AddTempData();
services.TryAddScoped();
RegisterPersistentComponentStateServiceCollectionExtensions.AddPersistentServiceRegistration(services, RenderMode.InteractiveWebAssembly);
diff --git a/src/Components/Endpoints/src/DependencyInjection/RazorComponentsServiceOptions.cs b/src/Components/Endpoints/src/DependencyInjection/RazorComponentsServiceOptions.cs
index de13d40cc46b..85e883dde0d9 100644
--- a/src/Components/Endpoints/src/DependencyInjection/RazorComponentsServiceOptions.cs
+++ b/src/Components/Endpoints/src/DependencyInjection/RazorComponentsServiceOptions.cs
@@ -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;
@@ -83,5 +84,23 @@ public TimeSpan TemporaryRedirectionUrlValidityDuration
}
}
+ ///
+ /// Determines the settings used to create the TempData cookie.
+ ///
+ public CookieBuilder TempDataCookie { get; set; } = new()
+ {
+ Name = CookieTempDataProvider.CookieName,
+ HttpOnly = true,
+ SameSite = SameSiteMode.Lax,
+ IsEssential = false,
+ SecurePolicy = CookieSecurePolicy.SameAsRequest,
+ };
+
internal string? JavaScriptInitializers { get; set; }
+
+ ///
+ /// Gets or sets the storage provider type for TempData.
+ /// Defaults to .
+ ///
+ public TempDataProviderType TempDataProviderType { get; set; } = TempDataProviderType.Cookie;
}
diff --git a/src/Components/Endpoints/src/DependencyInjection/TempDataService.cs b/src/Components/Endpoints/src/DependencyInjection/TempDataService.cs
new file mode 100644
index 000000000000..5cbf722c6bc3
--- /dev/null
+++ b/src/Components/Endpoints/src/DependencyInjection/TempDataService.cs
@@ -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 Load(HttpContext httpContext)
+ {
+ return _tempDataProvider.LoadTempData(httpContext);
+ }
+
+ public void Save(HttpContext httpContext, TempData tempData)
+ {
+ if (!tempData.WasLoaded)
+ {
+ return;
+ }
+ _tempDataProvider.SaveTempData(httpContext, tempData.Save());
+ }
+}
diff --git a/src/Components/Endpoints/src/Microsoft.AspNetCore.Components.Endpoints.csproj b/src/Components/Endpoints/src/Microsoft.AspNetCore.Components.Endpoints.csproj
index de0329c94e63..f7f81a895f59 100644
--- a/src/Components/Endpoints/src/Microsoft.AspNetCore.Components.Endpoints.csproj
+++ b/src/Components/Endpoints/src/Microsoft.AspNetCore.Components.Endpoints.csproj
@@ -32,7 +32,9 @@
+
+
diff --git a/src/Components/Endpoints/src/PublicAPI.Unshipped.txt b/src/Components/Endpoints/src/PublicAPI.Unshipped.txt
index ac1780ba883e..2ebef8b69595 100644
--- a/src/Components/Endpoints/src/PublicAPI.Unshipped.txt
+++ b/src/Components/Endpoints/src/PublicAPI.Unshipped.txt
@@ -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?
diff --git a/src/Components/Endpoints/src/TempData/CookieTempDataProvider.cs b/src/Components/Endpoints/src/TempData/CookieTempDataProvider.cs
new file mode 100644
index 000000000000..05c95a6b4ff0
--- /dev/null
+++ b/src/Components/Endpoints/src/TempData/CookieTempDataProvider.cs
@@ -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 _logger;
+
+ public CookieTempDataProvider(
+ IDataProtectionProvider dataProtectionProvider,
+ IOptions options,
+ ITempDataSerializer tempDataSerializer,
+ ILogger logger)
+ {
+ _dataProtector = dataProtectionProvider.CreateProtector(Purpose);
+ _spanDataProtector = _dataProtector as ISpanDataProtector;
+ _tempDataSerializer = tempDataSerializer;
+ _options = options.Value;
+ _chunkingCookieManager = new ChunkingCookieManager();
+ _logger = logger;
+ }
+
+ public IDictionary 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.Empty;
+ }
+ var serializedDataFromCookie = _chunkingCookieManager.GetRequestCookie(context, cookieName);
+ if (serializedDataFromCookie is null)
+ {
+ return ReadOnlyDictionary.Empty;
+ }
+
+ byte[]? rentedDecodeBuffer = null;
+ var maxDecodedSize = Base64Url.GetMaxDecodedLength(serializedDataFromCookie.Length);
+ var decodeBuffer = maxDecodedSize <= 256
+ ? stackalloc byte[256]
+ : (rentedDecodeBuffer = ArrayPool.Shared.Rent(maxDecodedSize));
+
+ try
+ {
+ var decodeStatus = Base64Url.DecodeFromChars(serializedDataFromCookie, decodeBuffer, out _, out var bytesWritten);
+ var protectedBytes = decodeBuffer[..bytesWritten];
+ Dictionary? dataFromCookie;
+
+ if (_spanDataProtector is not null)
+ {
+ var unprotectBuffer = new RefPooledArrayBufferWriter(stackalloc byte[256]);
+ _spanDataProtector.Unprotect(protectedBytes, ref unprotectBuffer);
+ dataFromCookie = JsonSerializer.Deserialize>(unprotectBuffer.WrittenSpan);
+ }
+ else
+ {
+ var unprotectedBytes = _dataProtector.Unprotect(protectedBytes.ToArray());
+ dataFromCookie = JsonSerializer.Deserialize>(unprotectedBytes);
+ }
+
+ if (dataFromCookie is null)
+ {
+ return ReadOnlyDictionary.Empty;
+ }
+ var convertedData = _tempDataSerializer.DeserializeData(dataFromCookie);
+ Log.TempDataCookieLoadSuccess(_logger, cookieName);
+ return convertedData;
+ }
+ finally
+ {
+ if (rentedDecodeBuffer is not null)
+ {
+ ArrayPool.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.Empty;
+ }
+ }
+
+ public void SaveTempData(HttpContext context, IDictionary 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;
+ }
+ }
+ }
+
+ 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);
+ }
+}
diff --git a/src/Components/Endpoints/src/TempData/ITempData.cs b/src/Components/Endpoints/src/TempData/ITempData.cs
new file mode 100644
index 000000000000..70f637e7af6e
--- /dev/null
+++ b/src/Components/Endpoints/src/TempData/ITempData.cs
@@ -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;
+
+///
+/// Provides a dictionary for storing data that is needed for subsequent requests.
+/// Data stored in TempData is automatically removed after it is read unless
+/// or is called, or it is accessed via .
+///
+public interface ITempData : IDictionary
+{
+ ///
+ /// Gets the value associated with the specified key and then schedules it for deletion.
+ ///
+ object? Get(string key);
+
+ ///
+ /// Gets the value associated with the specified key without scheduling it for deletion.
+ ///
+ object? Peek(string key);
+
+ ///
+ /// Makes all of the keys currently in TempData persist for another request.
+ ///
+ void Keep();
+
+ ///
+ /// Makes the element with the persist for another request.
+ ///
+ void Keep(string key);
+}
diff --git a/src/Components/Endpoints/src/TempData/ITempDataSerializer.cs b/src/Components/Endpoints/src/TempData/ITempDataSerializer.cs
new file mode 100644
index 000000000000..cab8c4af1ca8
--- /dev/null
+++ b/src/Components/Endpoints/src/TempData/ITempDataSerializer.cs
@@ -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 DeserializeData(IDictionary data);
+
+ public byte[] SerializeData(IDictionary data);
+
+ public bool CanSerialize(Type type);
+}
diff --git a/src/Components/Endpoints/src/TempData/JsonTempDataSerializer.cs b/src/Components/Endpoints/src/TempData/JsonTempDataSerializer.cs
new file mode 100644
index 000000000000..4e3c770dae32
--- /dev/null
+++ b/src/Components/Endpoints/src/TempData/JsonTempDataSerializer.cs
@@ -0,0 +1,195 @@
+// Licensed to the .NET Foundation under one or more agreements.
+// The .NET Foundation licenses this file to you under the MIT license.
+
+using System.Globalization;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Microsoft.AspNetCore.Components.Endpoints;
+
+internal class JsonTempDataSerializer : ITempDataSerializer
+{
+ public IDictionary DeserializeData(IDictionary data)
+ {
+ var dataDict = new Dictionary(data.Count);
+ foreach (var kvp in data)
+ {
+ dataDict[kvp.Key] = DeserializeElement(kvp.Value);
+ }
+ return dataDict;
+ }
+
+ private static object? DeserializeElement(JsonElement element)
+ {
+ return element.ValueKind switch
+ {
+ JsonValueKind.Null => null,
+ JsonValueKind.True => true,
+ JsonValueKind.False => false,
+ JsonValueKind.Number => element.GetInt32(),
+ JsonValueKind.String => DeserializeString(element),
+ JsonValueKind.Array => DeserializeArray(element),
+ JsonValueKind.Object => DeserializeObject(element),
+ _ => throw new NotSupportedException($"Unsupported JSON value kind: {element.ValueKind}")
+ };
+ }
+
+ private static object? DeserializeString(JsonElement element)
+ {
+ var type = GetStringType(element);
+ return type switch
+ {
+ Type t when t == typeof(Guid) => element.GetGuid(),
+ Type t when t == typeof(DateTime) => element.GetDateTime(),
+ _ => element.GetString(),
+ };
+ }
+
+ private static object? DeserializeArray(JsonElement element)
+ {
+ var length = element.GetArrayLength();
+ if (length == 0)
+ {
+ return Array.Empty