星期日, 8月 16, 2009

C# 實現Webclient保持Session的方法

最近使用webclient在實現非同步上傳的功能,
但server端由於會驗證session值是否已存在,
即存取 A.aspx 頁面後會產生一個session,
再存取 B.aspx 頁面後會驗證A.aspx產生的session,
而原本的webclient是沒有辦法保持session,
因此需要透過繼承webclient物件改寫其中的 GetWebRequest
並將需保持的session透過CookieContainer來保存,
即可實現。

namespace BigdControls
{
    public class HttpWebClient:WebClient
    {
        // Cookie 容器
        private CookieContainer cookieContainer;

        public HttpWebClient()
        {
            this.cookieContainer = new CookieContainer();
        }

        public HttpWebClient(CookieContainer cc)
        {
            this.cookieContainer = cc;
        }

        /// <summary>
        /// Cookie 容器
        /// </summary>
        public CookieContainer MyCookies
        {
            get { return this.cookieContainer; }
            set { this.cookieContainer = value; }
        }

        /// <summary>
        /// 覆寫web request方法,讓webclient能保持session
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        protected override WebRequest GetWebRequest(Uri address)
        {
            //throw new Exception(); 
            WebRequest request ;
            request = base.GetWebRequest(address);
            //判斷是不是HttpWebRequest.只有HttpWebRequest才有此属性 
            if (request is HttpWebRequest)
            {
                HttpWebRequest httpRequest = request as HttpWebRequest;
                httpRequest.CookieContainer = this.cookieContainer;
            }
                return request;
            }
        }
}

Reference:
实现支持会话的WebClient

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails