【问题标题】:Cookie doesn't get saved in ASP.NET WebMethodCookie 没有保存在 ASP.NET WebMethod 中
【发布时间】:2016-01-01 00:59:48
【问题描述】:

我正在尝试将 cookie 保存在 WebMethod 中并在 Page_Load 时检索它。但是,cookie 不会被保存,它会在 Page_Load 事件中返回 null。

这是我的代码:

网络方法

[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"];
    }
}

我做错了什么?

【问题讨论】:

  • 也给出到期日期
  • HttpContext.Current.Response.Cookies["userdata"].Expires = DateTime.Now.AddDays(1);
  • 是否需要过期?我需要存储一个身份验证令牌@DannyFardyJhonstonBermúdez

标签: c# asp.net cookies asp.net-web-api webmethod


【解决方案1】:

您通过键 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);
}

【讨论】:

  • 对不起,这是我的错误。代码还是不行
  • WebMethod 是否与您尝试检索它的 Page_Load 在同一主机服务器上运行?您是否尝试按照其他人的建议设置过期日期?
猜你喜欢
  • 2014-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-27
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
相关资源
最近更新 更多