WebClient 객체에 쿠키(Cookie)를 사용하는 방법
.NET의 경우 쿠키를 요청 간에 연속해서 다룰 때 CookieContainer를 이용하면 됩니다. 그런데, 아쉽게도 WebClient 객체는 CookieContainer를 접근할 수 있는 방법을 제공하지 않습니다.
그래도 검색해 보니 답이 나오는군요. ^^
Using a Cookie-Aware WebClient to Persist Authentication in ASP.NET MVC
; http://rionscode.wordpress.com/2013/07/22/using-a-cookie-aware-webclient-to-persist-authentication-in-asp-net-mvc/
방법은, WebClient를 상속받아 GetWebRequest 메서드를 재정의하는 것입니다. 따라서, 대략 다음과 같이 클래스를 만들어 사용하면 됩니다.
using System;
using System.Net;
class Program
{
static void Main(string[] args)
{
string path = "http://www.naver.com";
CookieAwareWebClient wc = new CookieAwareWebClient();
wc.DownloadStringCompleted += (s, e) =>
{
Console.WriteLine(e.Result);
};
wc.DownloadStringAsync(new Uri(path));
Console.WriteLine("Exit... ");
Console.ReadLine();
}
}
// http://rionscode.wordpress.com/2013/07/22/using-a-cookie-aware-webclient-to-persist-authentication-in-asp-net-mvc/
class CookieAwareWebClient : WebClient
{
private CookieContainer cc = new CookieContainer();
private string lastPage;
protected override WebRequest GetWebRequest(System.Uri address)
{
WebRequest R = base.GetWebRequest(address);
if (R is HttpWebRequest)
{
HttpWebRequest WR = (HttpWebRequest)R;
Cookie cookie = new Cookie("TEST", "1");
cookie.Domain = address.Host;
cc.Add(cookie);
WR.CookieContainer = cc;
if (lastPage != null)
{
WR.Referer = lastPage;
}
}
lastPage = address.ToString();
return R;
}
}
그래도, 기왕에 ^^ 속성으로 제공해주었으면 좋지 않았을까 하는 아쉬움이 남는군요.
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]