如何解析HttpWebResponse.Headers.Keys返回Set-Cookie会话标识 [英] How to parse HttpWebResponse.Headers.Keys for a Set-Cookie session id returned

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

问题描述

我试图创建一个HttpWebRequest / HttpWebResponse会话与ASP.NET网站,以后通过url params解析一个HTML表单(这部分我知道如何做),但我不明白如何解析和设置cookie如会话id。在Fiddler中,它显示通过Set-Cookie在对URL的/路径的请求的响应中返回ASP.NET会话ID,但是如何提取此会话ID并将其设置为下一个HttpWebRequest的cookie ?我理解这个Set-Cookie头可以在HttpWebResponse.Headers.Keys中找到,但是有一个直接的路径来解析它吗?谢谢!

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!

推荐答案

.NET框架将为您管理Cookie。

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.

要存储和发送会话ID,请使用 Cookie CookieContainer 类来存储它们,然后确保每次请求都发送您的Cookie。

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.

以下示例演示如何执行此操作。 CookieContainer,' cookieJar '可以跨多个域和请求共享。一旦将它添加到请求对象中,在返回响应时,对它的引用也将被添加到响应对象中。

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);
}

此代码的输出将是:


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

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

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

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