【问题标题】:How to read a cookie in angularjs, after it was set in Web Api在 Web Api 中设置后,如何在 angularjs 中读取 cookie
【发布时间】:2014-10-23 14:49:18
【问题描述】:

我正在使用 FormsAuthenticationTicket 在 web api 中生成一个令牌, 像这样:

var user_json_str = new JavaScriptSerializer().Serialize(user);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
    user.UserId,
    DateTime.Now,
    DateTime.Now.AddMinutes(30), false,
    user_json_str, FormsAuthentication.FormsCookiePath);

string encTicket = FormsAuthentication.Encrypt(ticket);//ENCRYPT THE TICKET

之后,我尝试在响应标头中将其返回给用户:

HttpContext.Current.Response.Cookies.Add(new HttpCookie("encTicket", encTicket));

之后我在客户端找到了cookie。

我在某处读到,不建议使用这样的 web api,所以我尝试了这种方式:

string encTicket = FormsAuthentication.Encrypt(ticket);//ENCRYPT THE TICKET
HttpResponseMessage ans = new HttpResponseMessage();
ans = new HttpResponseMessage(HttpStatusCode.OK);
ans.Content = new StringContent("Logged");
ans.Headers.AddCookies(new[] { new CookieHeaderValue("encTicket", encTicket) });
return ans;

这次 cookie 没有出现在客户端(我尝试在 chrome 控制台中使用 document.cookie 读取它)。

从 web api 的响应头中发送 cookie 的正确方法是什么?

【问题讨论】:

  • 但如果我在控制台中打印:document.cookie 它已经显示了页面上存在的所有 cookie。我认为 $cookie 不会显示其他隐藏的 cookie。
  • 无论如何我都尝试了您的建议,但正如我所想,cookie 未定义。我的问题不是读取cookie,而是确保它到达客户端
  • 检查响应头,它是否显示在那里?
  • 当我使用 chrome 的“网络”选项卡读取响应时,它会显示。但在 javascript 中它是不存在的

标签: javascript angularjs asp.net-web-api


【解决方案1】:

您是否尝试过以下操作?

ans.Headers.AddCookies(new[] { new CookieHeaderValue("encTicket", encTicket)
{
  Expires = new DateTimeOffset( DateTime.Now.AddYears(1)),Path = "/"
} });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-27
    • 2022-07-07
    • 1970-01-01
    • 2017-10-28
    • 2012-07-05
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    相关资源
    最近更新 更多