2013-01-18 2 views
1

폼 인증 MVC 작업을 호출해야하는 Windows 응용 프로그램이 있습니다. 문제는 양식 인증 MVC 응용 프로그램으로 Windows 응용 프로그램에서 호출을 인증하는 방법을 잘 모르겠습니다.폼 또는 기본 인증

다음 코드는 로그인 페이지를 반환합니다. 어떤 방법 으로든 아래의 코드가 폼 인증을 사용하도록 허용하는 방법이 있습니까? 아니면 기본 인증을 사용하는 새로운 웹 API 프로젝트를 만들어야합니까?

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

var res = req.GetResponse(); 

당신은 로그온 작용에 의해 방출되고있는 FormsAuthentication 쿠키를 저장하는 CookieContainer을 사용할 수 있습니다, 당신의 도움을 주셔서

리처드 휴즈

+0

당신이 달성하려고하는 무엇 : 예를 들어

? 나는 네 목표가 무엇인지 뜻? – Silagy

+0

폼 인증 된 MVC 작업을 호출해야하는 Windows 응용 프로그램이 있습니다. 문제는 양식 인증 MVC 응용 프로그램으로 Windows 응용 프로그램에서 인증하는 방법을 모르겠습니다. – rhughes

답변

3

를 대단히 감사합니다. 따라서 기본적으로 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