Cookies
in a HttpWebRequest
are read-only but I need to change some of cookies.
I can use Set-Cookie
header but it's error-prone. Is there anyway to change a HttpWebRequest
cookies in a OO
way ?
If no, how can I 开发者_JAVA技巧get the header text of a System.Net.Cookie
? (I will use it in Set-Cookie
header)
HttpWebRequest targetrequest = (HttpWebRequest)WebRequest.Create(targeturl);
targetrequest.CookieContainer = new CookieContainer();
foreach (string clientcookie in Request.Cookies) {
Cookie targetcookie = new Cookie(clientcookie, Request.Cookies[clientcookie].Value, "/", targetrequest.RequestUri.Host);
targetrequest.CookieContainer.Add(targetcookie);
}
Have a look at http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.cookiecontainer(v=VS.90).aspx
You need to initialize the CookieContainer object and add your cookies to it.
If you get cookies from a HttpWebResponse simply add the collection to the CookieContainer (see: http://msdn.microsoft.com/en-us/library/system.net.cookiecontainer.add(v=VS.90).aspx).
To change one specific cookie you should access it and change its values:
cookies["cookie_name"].Expiration = ...
精彩评论