Sending cookies using HttpCookieCollection and CookieContainer

前端 未结 3 1705
执笔经年
执笔经年 2020-12-15 05:00

I want to tunnel through an HTTP request from my server to a remote server, passing through all the cookies. So I create a new HttpWebRequest object and want t

3条回答
  •  星月不相逢
    2020-12-15 05:27

    I had a need to do this today for a SharePoint site which uses Forms Based Authentication (FBA). If you try and call an application page without cloning the cookies and assigning a CookieContainer object then the request will fail.

    I chose to abstract the job to this handy extension method:

    public static CookieContainer GetCookieContainer(this System.Web.HttpRequest SourceHttpRequest, System.Net.HttpWebRequest TargetHttpWebRequest)
        {
            System.Web.HttpCookieCollection sourceCookies = SourceHttpRequest.Cookies;
            if (sourceCookies.Count == 0)
                return null;
            else
            {
                CookieContainer cookieContainer = new CookieContainer();
                for (int i = 0; i < sourceCookies.Count; i++)                
                {
                    System.Web.HttpCookie cSource = sourceCookies[i];
                    Cookie cookieTarget = new Cookie() { Domain = TargetHttpWebRequest.RequestUri.Host, 
                                                         Name = cSource.Name, 
                                                         Path = cSource.Path, 
                                                         Secure = cSource.Secure, 
                                                         Value = cSource.Value };
                    cookieContainer.Add(cookieTarget);
                }
                return cookieContainer;
            }
        }
    

    You can then just call it from any HttpRequest object with a target HttpWebRequest object as a parameter, for example:

    HttpWebRequest request;                
    request = (HttpWebRequest)WebRequest.Create(TargetUrl);
    request.Method = "GET";
    request.Credentials = CredentialCache.DefaultCredentials;
    request.CookieContainer = SourceRequest.GetCookieContainer(request);                
    request.BeginGetResponse(null, null);
    

    where TargetUrl is the Url of the page I am after and SourceRequest is the HttpRequest of the page I am on currently, retrieved via Page.Request.

提交回复
热议问题