一个 ASP.NET Core 应用从 .NET 6 升级至 .NET 7 之后,日志中出现很多错误 "Nullable object must have a value"
System.InvalidOperationException: Nullable object must have a value.
at Microsoft.Net.Http.Headers.CookieHeaderParserShared.TryParseValues(StringValues values, IDictionary`2 store, Boolean enableCookieNameEncoding, Boolean supportsMultipleValues)
at Microsoft.AspNetCore.Http.RequestCookieCollection.ParseInternal(StringValues values, Boolean enableCookieNameEncoding)
at Microsoft.AspNetCore.Http.Features.RequestCookiesFeature.get_Cookies()
at Microsoft.AspNetCore.Authentication.Cookies.ChunkingCookieManager.GetRequestCookie(HttpContext context, String key)
at Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.ReadCookieTicket()
at Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler.HandleAuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
at Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext context, String scheme)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
多数是 GA 的 cookie 引起的
Hm_lvt_866c9be12d4a814454792b1fd0fed295=1657263589,1659088360,1659419877,1659521677;
在 https://github.com/dotnet/aspnetcore/pull/45127 中已经修复了这个问题,但可能要等到 .NET 8 才会发布
写了个中间件临时避开这个问题
public class CheckCookiesMiddleware
{
private readonly RequestDelegate _next;
public CheckCookiesMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext httpContext)
{
try
{
var cookies = httpContext.Request.Cookies;
}
catch (Exception ex) when (ex.Message.Contains("Nullable object must have a value"))
{
var logger = httpContext.RequestServices.GetRequiredService<ILogger<CheckCookiesMiddleware>>();
var cookies = httpContext.Request.Headers[HeaderNames.Cookie];
logger.LogInformation("Removing invalid Cookies: \n{cookies}", cookies);
httpContext.Request.Headers[HeaderNames.Cookie] = string.Empty;
}
await _next(httpContext);
}
}
@dudu: .NET 7.0.3 今天发布了,这个问题在 Fix cookie null regression 中修复了