2011-03-28 112 views
0

我有一個使用wcf rest服務的asp mvc應用程序(全部在同一個盒子上)。對於身份驗證呼叫, 我正嘗試在一個wcf rest服務中設置cookie。在客戶端在wcf服務中設置cookie

碼 -

 HttpResponseMessage resp; 
     HttpClient client = new HttpClient("http://localhost/auth/login/"); 
     resp = client.Get(); 

在web服務我只是用FormsAuthentication設置一個authcookie。

 HttpCookie authCookie = FormsAuthentication.GetAuthCookie("foo", false); 
     HttpContext.Current.Response.Cookies.Add(authCookie); 

假設憑據是硬編碼的代碼 - 如果我物理導航到browserpage

 http://localhost/auth/login 

(代碼中的硬編碼的憑據),我可以看到的是,身份驗證cookie被設置。但是,如果我只是通過代碼調用它(如上所示),則不會設置身份驗證cookie。

有什麼明顯的,我在這裏俯瞰?

回答

1

當您以編程方式調用WCF服務時,它設置的cookie存儲在HttpClient實例中。客戶端瀏覽器從不會看到它,所以它永遠不會被設置在它內部。所以你需要手動設置:

using (var client = new HttpClient("http://localhost/auth/login/")) 
{ 
    var resp = client.Get(); 
    // Once you get the response from the remote service loop 
    // through all the cookies and append them to the response 
    // so that they are stored within the client browser. 
    // In this collection you will get all Set-Cookie headers 
    // sent by the service, so find the one you need and set it: 
    foreach (var cookie in result.Headers.SetCookie) 
    { 
     // the name of the cookie must match the name of the authentication 
     // cookie as you set it in your web.config. 
     var data = cookie["SomeCookieName"]; 
     Response.AppendCookie(new HttpCookie("SomeCookieName", data)); 
    } 
} 
+0

謝謝達林。這工作。將.aspxauth cookie的名稱更改爲服務器中的其他名稱導致它不能設置,但這是另一個問題... :) – user275157 2011-03-29 16:55:03