66using Microsoft . AspNetCore . Http ;
77using Microsoft . AspNetCore . WebUtilities ;
88using Microsoft . Extensions . DependencyInjection ;
9+ using Microsoft . Extensions . Logging ;
910
1011namespace Microsoft . AspNetCore . Components . Endpoints ;
1112
12- internal sealed class TempDataService
13+ internal sealed partial class TempDataService
1314{
1415 private const string CookieName = ".AspNetCore.Components.TempData" ;
1516 private const string PurposeString = "Microsoft.AspNetCore.Components.Endpoints.TempDataService" ;
@@ -33,6 +34,7 @@ public static TempData Load(HttpContext httpContext)
3334
3435 var protectedBytes = WebEncoders . Base64UrlDecode ( serializedDataFromCookie ) ;
3536 var unprotectedBytes = GetDataProtector ( httpContext ) . Unprotect ( protectedBytes ) ;
37+
3638 var dataFromCookie = JsonSerializer . Deserialize < Dictionary < string , JsonElement > > ( unprotectedBytes ) ;
3739
3840 if ( dataFromCookie is null )
@@ -49,10 +51,15 @@ public static TempData Load(HttpContext httpContext)
4951 returnTempData . Load ( convertedData ) ;
5052 return returnTempData ;
5153 }
52- catch
54+ catch ( Exception ex )
5355 {
5456 // If any error occurs during loading (e.g. data protection key changed, malformed cookie),
5557 // return an empty TempData dictionary.
58+ if ( httpContext . RequestServices . GetService < ILogger < TempDataService > > ( ) is { } logger )
59+ {
60+ Log . TempDataCookieLoadFailure ( logger , CookieName , ex ) ;
61+ }
62+
5663 httpContext . Response . Cookies . Delete ( CookieName , new CookieOptions
5764 {
5865 Path = httpContext . Request . PathBase . HasValue ? httpContext . Request . PathBase . Value : "/" ,
@@ -177,4 +184,10 @@ private static bool CanSerializeType(Type type)
177184 typeof ( ICollection < string > ) . IsAssignableFrom ( type ) ||
178185 typeof ( IDictionary < string , string > ) . IsAssignableFrom ( type ) ;
179186 }
187+
188+ private static partial class Log
189+ {
190+ [ LoggerMessage ( 3 , LogLevel . Warning , "The temp data cookie {CookieName} could not be loaded." , EventName = "TempDataCookieLoadFailure" ) ]
191+ public static partial void TempDataCookieLoadFailure ( ILogger logger , string cookieName , Exception exception ) ;
192+ }
180193}
0 commit comments