首页 新闻 会员 周边

升级至 .NET 7 后日志中很多错误:"Nullable object must have a value"

0
悬赏园豆:30 [已解决问题] 解决于 2022-12-17 22:15

一个 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;
dudu的主页 dudu | 高人七级 | 园豆:30994
提问于:2022-12-17 15:28
< >
分享
最佳答案
0

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 | 高人七级 |园豆:30994 | 2022-12-17 22:14

@dudu: .NET 7.0.3 今天发布了,这个问题在 Fix cookie null regression 中修复了

dudu | 园豆:30994 (高人七级) | 2023-02-15 07:03
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册