无法在 ASP.NET MVC 下使用 C# 设置和获取 cookie

Can't Set and Get cookie using C# under ASP.NET MVC

我正在尝试在 C# 中设置和读取 cookie。我写了这两个方法:

public static void setCookie(string sCookie, string value)
{
    HttpCookie cookie = HttpContext.Current.Request.Cookies[sCookie];
    if (cookie == null)
        cookie = new HttpCookie(sCookie);
    cookie.Value = value;
    cookie.Expires = DateTime.Now.AddYears(1);
    HttpContext.Current.Request.Cookies.Add(cookie);
}

public static string getCookie(string sCookie)
{
    if (HttpContext.Current.Request.Cookies[sCookie] == null)
        return null;
    return HttpContext.Current.Request.Cookies[sCookie].Value;
}

但我不知道为什么当我读取getCookie方法时,在调用setCookie之后,集合HttpContext.Current.Request.Cookies总是包含2个元素,“__RequestVerificationToken”和"ASP.NET_SessionId",它不包含我的饼干...

方法不在任何控制器中,只在实用程序中 class,但我看不出有任何问题...

你能找出为什么我的设置方法不起作用吗? 谢谢!

将 cookie 设置为 Response 对象,同时设置 cookie 的路径