【问题标题】:How to port cookie.Value from .NET 5 to .NET 6/7? (ASP.NET CORE)如何将 cookie.Value 从 .NET 5 移植到 .NET 6/7? (ASP.NET 核心)
【发布时间】:2022-11-21 22:23:58
【问题描述】:

有问题的代码是:

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

我根据文档尝试了以下语法,但它似乎不起作用。

var arrVal = cookie["Value"].Split('.');

对于代码的上下文其余部分:

public IList<CookieType> GetAcceptedCookieTypes(HttpContext httpContext)
        {
            var result = new List<CookieType>();
            // accepted by default
            result.Add(CookieType.Essential);

            var cookie = httpContext.Request.Cookies["cc_cookie_accept"];
            if (cookie != null)
            {
                var arrVal = cookie.Value.Split('.');
                if (arrVal != null && arrVal.Length > 1)
                {
                    var arrCheck = arrVal[1];
                    if (arrCheck.Length > 0 && arrCheck[0] == '1')
                    {
                        result.Add(CookieType.Statistical);
                    }
                }
            }
            return result;
        }

我得到的错误:

CS1061: 'string' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

【问题讨论】:

  • 我不知道 ASP.NET Core 5 和 6 之间的 cookie 有任何变化。你得到了什么错误,确切地说?
  • @Dai 更新了问题。
  • 我检查了文档和IRequestCookieCollection[String]has always returned string? going back to ASP.NET Core 1.0。您的代码无法编译 against ASP.NET Core 5.0,其中唯一的更改是添加可空注释。
  • 反正。要修复它,只需删除 .Value 部分。
  • 我注意到在 ASP.NET for .NET Framework (2001-2015) 中 Request.Cookies 集合做过返回 System.Web.HttpCookie 对象有一个 .Value 属性,但这根本不是 .NET 5。

标签: c# asp.net-core .net-core cookies split


【解决方案1】:

我检查了文档和IRequestCookieCollection[String]has always returned string? going back to ASP.NET Core 1.0。您的代码无法编译 against ASP.NET Core 5.0,其中唯一的更改是添加可为 null 的注释。

我注意到在 ASP.NET for .NET Framework (2001-2015) 中 Request.Cookies 集合做过返回 System.Web.HttpCookie objects which do have a .Value property,但这根本不是 .NET 5。

反正。要修复它,只需删除 .Value 部分。

【讨论】:

    猜你喜欢
    • 2016-04-10
    • 1970-01-01
    • 2020-04-20
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2019-02-17
    • 2017-10-23
    相关资源
    最近更新 更多