Asp.netMvc中如何保存和读取Cookie

How to save and read Cookie in Asp.net Mvc

我将我的 cookie 保存为以下代码:

public static void SetCookie(string key, string value, int expireDay = 1)
{
        var cookie = new HttpCookie(key , value);
        cookie.Expires = DateTime.Now.AddDays(expireDay);
        HttpContext.Current.Response.Cookies.Add(cookie);
}

存储时的cookie值如下:

读取 Cookie:

public static string GetCookie(string key)
{
        string value = string.Empty;

        var cookie = HttpContext.Current.Request.Cookies[key];

        if (cookie != null)
        {
            if (string.IsNullOrWhiteSpace(cookie.Value))
            {
                return value;
            }
            value = cookie.Value;
        }

        return value;
}

问题是读取 cookie 时,所有值都是空的,如下图所示:

实际上你应该从请求头中读取cookies;没有回应!

问题在这里:HttpContext.Current.Response.Cookies.AllKeys.Contains(key)。 您需要从请求中读取它。并将更改写入响应。

这是一个更简单的工作示例,它只打印“嘿!”,并在每个 GET 上附加一个感叹号:

    public class IndexModel : PageModel
    {
        public string CookieValue = "Hey!";
        private const string COOKIE_KEY = "HEY_COOKIE";

        public void OnGet()
        {
            Request.Cookies.TryGetValue(COOKIE_KEY, out string? actualValue);
            if (actualValue is not null) CookieValue = actualValue + "!";

            // Only required since we're changing the cookie
            // TODO: set the right cookie options
            Response.Cookies.Append(COOKIE_KEY, CookieValue, new CookieOptions { }); 
        }
    }
@page
@model IndexModel

<h1>@Model.CookieValue</h1>

此外,在通过 HTTP 进行调试时,查看 Chrome 的网络选项卡也很有用。

你的问题是你使用了HttpContext.Current.Response。取而代之的是,您应该像这样在 SetCookie 方法中声明一个参数:HttpContext 上下文,然后在控制器中,当您调用该方法时,您必须将 HttpContext 控制器 属性 作为参数发送。

public static void SetCookie(HttpContext context, string key, string value, int expireDay = 1)
{
        var cookie = new HttpCookie(key , value);
        cookie.Expires = DateTime.Now.AddDays(expireDay);
        context.Response.Cookies.Add(cookie);
}

在控制器中:

SetCookie(HttpContext, yourKey,yourValue)

您还应该像这样更改 GetCookie 方法:

public static string GetCookie(HttpContext context,string key)
{
        string value = string.Empty;

        var cookie = context.Request.Cookies[key];

        if (cookie != null)
        {
            if (string.IsNullOrWhiteSpace(cookie.Value))
            {
                return value;
            }
            value = cookie.Value;
        }

        return value;
}

cookie 的最大大小为 4kb。