如何在angularjs中读取cookie,在WebApi中设置之后

How to read a cookie in angularjs, after it was set in Web Api

本文关键字:WebApi 之后 设置 读取 angularjs cookie      更新时间:2023-09-26

我正在使用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));

之后我在客户那里找到了饼干。

我在某个地方读到,不建议使用这样的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读取它)。

从webapi在响应头中发送cookie的正确方式是什么?

您尝试过以下操作吗?

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