在Web Api中设置后,如何读取angularjs中的cookie

时间:2014-08-29 14:53:29

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

我使用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。

我在某处读过,不建议像这样使用网络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的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您是否尝试过以下操作?

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