gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:59:53 25 4
gpt4 key购买 nike

我正在使用 FormsAuthenticationTicket 在 Web api 中生成 token ,像这样:

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

之后,我尝试在响应 header 中将其返回给用户,如下所示:

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 的响应 header 中发送 cookie 的正确方法是什么?

最佳答案

您尝试过以下操作吗?

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

关于javascript - 在 Web Api 中设置 cookie 后,如何在 angularjs 中读取 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25570853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com