Cookie 未保存在浏览器中

问题描述 投票:0回答:1

我尝试将数据存储在 cookie 中,但浏览器不保存 cookie。

代码附在此处,我正在尝试设置 cookie 数据。

public static void SetCookie(string key, string value)
{
    //Create a Cookie with a suitable Key.
    HttpCookie nameCookie = new HttpCookie(key);
    if (nameCookie != null)
    {
        nameCookie.Secure = true;

        nameCookie.SameSite = System.Web.SameSiteMode.Strict;
       
        //Set the Cookie value.
        nameCookie.Values[key] = value;
        //Set the Expiry date.
        nameCookie.Expires = DateTime.Now.AddDays(350);
        nameCookie.HttpOnly = true;
        
        nameCookie.Domain = HttpContext.Current.Request.Url.Host; //"localhost";
        //Add the Cookie to Browser.
        HttpContext.Current.Response.Cookies.Add(nameCookie);
    }
}

在这里您可以看到 cookie 不存在:

我想获取浏览器中存储的cookie,特别是Key = ClientID及其值。

c# cookies session-cookies
1个回答
0
投票

我不确定您为什么使用

HttpCookie
类,该类在 .NET Framework 4.8 中可用,但使用最新的 ASP.NET 版本,此代码设置响应的 cookie。请注意,它不是静态的,因为它访问
HttpContext
ControllerBase
属性。您可以定义继承自
ControllerBase
的基类,定义此方法在所有控制器中可用。
或者您可以将其添加到某些服务中以在整个应用程序中使用。

这是代码:

private void SetCookie(string key, string value)
{
    var cookieOptions = new CookieOptions()
    {
        SameSite = SameSiteMode.Strict,
        Secure = true,
        Expires = DateTime.Now.AddDays(350),
        Domain = HttpContext.Request.Host.Host,
    };

    HttpContext.Response.Cookies.Append(
        key,
        value,
        cookieOptions);
}

结果如下:

© www.soinside.com 2019 - 2024. All rights reserved.