我怎样才能在 asp.net mvc 方法中读取 cookie



我是asp.net mvc新手,想阅读cookie,为此目的,使用以下代码编写cookie:

Cookies.SaveCookies(validate);


不想在这种方法中读取cookie:

public static int CookiesReturn()
        {
            if (Request.Cookies["userName"] != null)
                return  Server.HtmlEncode(Request.Cookies["userName"].Value);
        }


但在Request.Cookies上的获取错误中:

无法解决请求

在这一行中,Server.HtmlEncode...也会收到此错误:

无法解决请求

问题是Controller类有一个名为 HttpContext 的公共属性(请参阅此处(。尝试在它前面加上 System.Web . HttpContext.Current.Response.Cookies[cookieName] .

所以你的代码是这样的

 public static int CookiesReturn()
 {
   HttpCookie cookie =HttpContext.Current.Response.Cookies["userName"];
   if (cookie  != null)
   string username = Server.HtmlEncode(cookie.Value);
  }

您可以在此链接中了解有关 cookie 的更多信息。

最新更新