You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 5迁移至.NET 6/7:ASP.NET Core中Cookie.Value移植问题

在ASP.NET Core中将.NET 5的Cookie.Value代码移植到.NET 6/7

问题根源

在.NET 6及后续版本中,HttpContext.Request.Cookies["cookieName"]的返回类型发生了变化:

  • .NET 5中,该调用返回包含Value属性的Cookie对象
  • .NET 6/7中,直接返回字符串类型的Cookie值,因此调用.Value会触发CS1061错误(字符串没有Value属性)

修复方案

直接移除.Value调用,因为cookie变量本身就是你需要的字符串值:

将原代码中的:

var arrVal = cookie.Value.Split('.');

修改为:

var arrVal = cookie.Split('.');

完整修正后的代码

public IList<CookieType> GetAcceptedCookieTypes(HttpContext httpContext)
{
    var result = new List<CookieType>();

    // 默认接受必要Cookie
    result.Add(CookieType.Essential);

    var cookie = httpContext.Request.Cookies["cc_cookie_accept"];

    if (cookie != null)
    {
        var arrVal = cookie.Split('.');

        if (arrVal != null && arrVal.Length > 1)
        {
            var arrCheck = arrVal[1];

            if (arrCheck.Length > 0 && arrCheck[0] == '1')
            {
                result.Add(CookieType.Statistical);
            }
        }
    }

    return result;
}

额外说明

你之前尝试的cookie["Value"]写法是错误的,因为此时cookie已经是字符串类型的Cookie值,并非字典或复杂对象,无需通过索引器取值。

内容的提问来源于stack exchange,提问作者Munchkin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 07:01:14