2014-08-29 28 views
1

我生成的Web API令牌設置後:如何讀取angularjs一個cookie,它是使用的FormsAuthenticationTicket, 一樣,在網絡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的正確方法是什麼?

+0

見http://stackoverflow.com/questions/18513818/angularjs-cookie-read-response-value – PSL 2014-08-29 14:59:06

+0

但如果我在控制檯打印:document.cookie中它已經顯示了所有提出的餅乾頁。我不認爲$ cookie會讓我看到其他隱藏的cookie。 – Lichte 2014-08-29 15:04:25

+0

無論如何,我嘗試了你的建議,正如我所想的那樣,cookie是未定義的。我的問題是不讀取cookie,但要確保它來到客戶端 – Lichte 2014-08-29 15:17:44

回答

0

您是否嘗試過以下方法?

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