views:

1399

answers:

2

Hi everyone, 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 Http**Web**Request object and want to set cookies on it.

Http**Web**Request.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?

Thanks! -Mike

+3  A: 

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;

    try
    {
     myRequest.CookieContainer.Add( oC );
    }
    catch ( Exception )
    {
    }
}
David
I think this technique will work, but I was really hoping for a solution that wouldn't involve copying each value over.
Mike
A: 

Hi,

The suggested from David is the right one. You need to copy. Just simply create function to copy repeatedly. HttpCookie and Cookie object is created to make sure we can differentiate both in its functionality and where it come. HttpCookie used between user and your proxy Cookie is used between your proxy and remote web server.

HttpCookie has less functionality since the cookie is originated from you and you know how to handle it. Cookie provide you to manage cookie received from web server. Like CookieContainer, it can be used to manage domain, path and expiry.

So user side and web server side is different and to connect it, sure you need to convert it. In your case, it just simply direct assignment.

Notice that CookieContainer has a bug on .Add(Cookie) and .GetCookies(uri) method.

See the details and fix here:

http://dot-net-expertise.blogspot.com/2009/10/cookiecontainer-domain-handling-bug-fix.html

CallMeLaNN

CallMeLaNN