我试图在 WebMethod 中保存一个 cookie 并在 Page_Load 时检索它。但是,cookie 不会被保存,它会在 Page_Load 事件中返回一个空值。
这是我的代码:
网络方法
[WebMethod]
public static string LoginUser(string email, string pass)
{
//more code
var ecookie= new HttpCookie("ecookie");
ecookie["name"] = "roger";
HttpContext.Current.Response.Cookies.Add(ecookie);
}
Page_Load
protected void Page_Load(object sender, EventArgs e)
{
var response = HttpContext.Current.Response;
if (response.Cookies["ecookie"]["name"] != null) //doesn't go inside this condition since it's null
{
string name = response.Cookies["ecookie"]["name"];
}
}
我做错了什么?
最佳答案
您通过键 userdata
保存 cookie 值,然后通过键 ecookie
检索它。
假设您想要使用 key ecookie
存储 cookie,您的 WebMethod
应该看起来像:
[WebMethod]
public static string LoginUser(string email, string pass)
{
//more code
var ecookie= new HttpCookie("ecookie");
ecookie["name"] = "roger";
HttpContext.Current.Response.Cookies.Add(ecookie);
}
关于c# - Cookie 不会保存在 ASP.NET WebMethod 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32930506/