如何解析HttpWebResponse.Headers.Keys为返回一个Set-Cookie的会话ID [英] How to parse HttpWebResponse.Headers.Keys for a Set-Cookie session id returned

查看:1371
本文介绍了如何解析HttpWebResponse.Headers.Keys为返回一个Set-Cookie的会话ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个ASP.NET网站上的HttpWebRequest / HttpWebResponse会议以后通过解析网址参数的HTML表单(这部分我知道该怎么做),但我不明白如何解析和设置饼干,如会话ID。在提琴手,它表明了ASP.NET会话ID在响应请求的URL /路径通过的Set-Cookie回来了,但我怎么能提取该会话ID并将其设置为在未来一个cookie的HttpWebRequest ?我明白这设置Cookie标头将在HttpWebResponse.Headers.Keys找到,但有一个直接的路径解析它?谢谢!


解决方案

在.NET框架将管理Cookie为您服务。你不必与解析cookie信息出来的头或添加一个cookie头对您的请求关心自己。



要存储和发送您的会话ID,使用 饼干 的CookieContainer 类存储它们,然后确保你的每个请求发送给您的Cookie。



下面的例子演示了如何做到这一点。该的CookieContainer, cookieJar 可以跨越多个域和请求共享。一旦你把它添加到一个请求对象,对它的引用也将被添加到时返回的响应响应对象。

 的CookieContainer cookieJar =新的CookieContainer(); 

VAR请求=(HttpWebRequest的)HttpWebRequest.Create(http://www.google.com);
request.CookieContainer = cookieJar;

VAR响应= request.GetResponse();

的foreach(曲奇℃的cookieJar.GetCookies(request.RequestUri))
{
Console.WriteLine(曲奇['+ c.Name +']: + c.Value);
}



这段代码的输出将是:


ID = 59e9a22a8cac2435:TM = 1246226400:LM = 1246226400:S = tvWTnbBhK4N7Tlpu <

饼干['PREF'] / p>

I'm trying to create an HttpWebRequest/HttpWebResponse session with an ASP.NET website to later parse an HTML form through url params (this part I know how to do), but I do not understand how to parse and set a cookie such as the session id. In Fiddler, it shows that the ASP.NET Session ID is returned through Set-Cookie in the response to the request to the / path of the url, but how can I extract this session id and set it as a cookie for the next HttpWebRequest? I understand that this Set-Cookie header would be found in HttpWebResponse.Headers.Keys, but is there a direct path to parsing it? Thanks!

解决方案

The .NET framework will manage cookies for you. You don't have to concern yourself with parsing the cookie information out of the headers or adding a cookie header to your requests.

To store and send your session ID, use the Cookie and CookieContainer classes to store them and then make sure you send your cookies with every request.

The following example shows how to do this. The CookieContainer, 'cookieJar' can be shared across multiple domains and requests. Once you add it to a request object, the reference to it will also be added to the response object when the response is returned.

CookieContainer cookieJar = new CookieContainer();

var request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
request.CookieContainer = cookieJar;

var response = request.GetResponse();

foreach (Cookie c in cookieJar.GetCookies(request.RequestUri))
{
    Console.WriteLine("Cookie['" + c.Name + "']: " + c.Value);
}

The output of this code will be:

Cookie['PREF']: ID=59e9a22a8cac2435:TM=1246226400:LM=1246226400:S=tvWTnbBhK4N7Tlpu

这篇关于如何解析HttpWebResponse.Headers.Keys为返回一个Set-Cookie的会话ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆