我将我的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:
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时,所有值都是空的,如下图所示:
实际上你应该从请求头中读取cookie;没有回复!
问题就在这里:
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;
}