Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

c# - Sending cookies using HttpCookieCollection and CookieContainer

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 to set cookies on it.

HttpWebRequest.CookieContainer is type System.Net.CookieContainer which holds System.Net.Cookies.

On my incoming request object:

HttpRequest.Cookies is type System.Web.HttpCookieCollection which holds System.Web.HttpCookies.

Basically I want to be able to assign them to each other, but the differing types makes it impossible. Do I have to convert them by copying their values, or is there a better way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's the code I've used to transfer the cookie objects from the incoming request to the new HttpWebRequest... ("myRequest" is the name of my HttpWebRequest object.)

HttpCookieCollection oCookies = Request.Cookies;
for ( int j = 0; j < oCookies.Count; j++ ) 
{
    HttpCookie oCookie = oCookies.Get( j );
    Cookie oC = new Cookie();

    // Convert between the System.Net.Cookie to a System.Web.HttpCookie...
    oC.Domain   = myRequest.RequestUri.Host;
    oC.Expires  = oCookie.Expires;
    oC.Name     = oCookie.Name;
    oC.Path     = oCookie.Path;
    oC.Secure   = oCookie.Secure;
    oC.Value    = oCookie.Value;

    myRequest.CookieContainer.Add( oC );
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...