2013-01-18 91 views
1

我有一個Windows應用程序需要調用Forms Authenticated MVC操作。問題是,我不確定如何將Windows應用程序的調用驗證到Forms Authenticated MVC應用程序中。表單或基本身份驗證

以下代碼返回登錄頁面。有沒有辦法允許下面的代碼通過任何方式使用Forms身份驗證,還是我需要創建一個新的Web API項目,使用基本身份驗證這個工作?

WebRequest req = WebRequest.Create("http://myurl/protectaction"); 
req.Credentials = new NetworkCredential("username", "password"); 

var res = req.GetResponse(); 

非常感謝您的幫助,

理查德·休斯

+0

你到底想達到什麼目的?我的意思是你的目標是什麼? – Silagy

+0

我有一個Windows應用程序需要調用一個表單身份驗證受保護的MVC操作。問題是,我不知道如何從Windows應用程序驗證到Forms Authenticated MVC應用程序。 – rhughes

回答

3

你可以使用一個CookieContainer來存儲由登錄動作發出的FormsAuthentication餅乾。因此,基本上,您將向LogOn操作發送第一個請求,然後爲隨後的請求重新使用相同的WebRequest實例。

這樣你將只通過電線發送你的憑證一次。

例如:

var container = new CookieContainer(); 

var req = (HttpWebRequest)WebRequest.Create("http://myurl/account/logon"); 
req.CookieContainer = container; 
req.Method = "POST"; 
using (var writer = new StreamWriter(req.GetRequestStream())) 
{ 
    var data = HttpUtility.ParseQueryString(string.Empty); 
    data["username"] = "john"; 
    data["password"] = "secret"; 
    writer.Write(data.ToString()); 
} 
using (var res = req.GetResponse()) 
{ 
    // You could check here if login was successful 
} 

req = (HttpWebRequest)WebRequest.Create("http://myurl/protectedresource"); 
req.CookieContainer = container; 
using (var res = req.GetResponse()) 
using (var reader = new StreamReader(res.GetResponseStream())) 
{ 
    string result = reader.ReadToEnd(); 
    // do something with the protected resource 
} 
+0

謝謝。我不得不補充: req.ContentType =「application/x-www-form-urlencoded」;讓它在我的情況下工作。 – rhughes