Cookie 未保存在 ASP.NET WebMethod 中

Cookie doesn't get saved in ASP.NET WebMethod

我正在尝试在 WebMethod 中保存一个 cookie 并在 Page_Load 上检索它。然而,cookie 没有被保存,它在 Page_Load 事件中 returns 为 null。

这是我的代码:

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);
}

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 检索它。

假设您要使用密钥 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);
}