如何检索c#中的所有cookie?

时间:2012-02-29 19:18:13

标签: c# cookies fiddler

根据fiddler的说法,我希望记录后可以使用这些cookie

Set-Cookie: JSESSIONID=value; Version=1; Domain=.domain.com.mx; Path=/
Set-Cookie: saplb_*=value; Version=1; Path=/
Set-Cookie: PortalAlias=portal; Path=/
Set-Cookie: MYSAPSSO2=value;path=/;domain=.domain.com.mx;HttpOnly

因此,我只是得到这个cookie:

Set-Cookie: PortalAlias=portal; Path=/

我有登录代码:

string url = "site.com";

string postdata = "user=username&pass=userpass";
byte[] buffer = Encoding.ASCII.GetBytes(postdata);


**// GET cookies from url
getCookies(url)**

// request
HttpWebRequest request = (HttpWebRequest)System.Net.WebRequest.Create(Url);
request.CookieContainer = this.cookies;

// post
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = buffer.Length;
using (Stream postdata_stream = request.GetRequestStream())
  postdata_stream.Write(buffer, 0, buffer.Length);


// response
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
  // here, I expect to receive 4 cookies, but I only get 1
  foreach (Cookie c in response.Cookies) 
  {
    log("Name:" + c.Name);
    log("Value:" + c.Value);
    log("");
    this.cookies.Add(new Cookie(c.Name, c.Value, c.Path, c.Domain));
  }
}

问题是,当我在提琴手中检查我的程序响应时,有4个cookie,但不是为什么我只能读一个。

更新

GET为Cookie添加的代码:

private void getCookies(string url)
{

  // request
  HttpWebRequest request = CreateWebRequestObject(url);
  request.CookieContainer = this.cookies; // protected member

  request.Method = "GET";
  request.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:10.0.2) Gecko/20100101 irefox/10.0.2";

  // response
  using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  {
    foreach (Cookie c in response.Cookies)
    {

        // add cookies to my CookieContainer
        this.cookies.Add(new Cookie(c.Name, c.Value, c.Path, c.Domain));
    }
  }
}

使用getCookies()我有3/4个cookie:

Set-Cookie: JSESSIONID=value; Version=1; Domain=.domain.com.mx; Path=/
Set-Cookie: saplb_*=value; Version=1; Path=/
Set-Cookie: PortalAlias=portal; Path=/

但仍然需要一个cookie:

Set-Cookie: MYSAPSSO2=value;path=/;domain=.domain.com.mx;HttpOnly

此外,我将请求与Fiddler / WinMerge进行比较:

// program request
$Version=1; saplb_*=value; $Path=/; $Version=1; JSESSIONID=value; $Path=/; Domain=.domain.com.mx
Expect: 100-continue

// firefox request
saplb_*=value; JSESSIONID=value
Connection: keep-alive

为什么我的请求中有“$”字符?

2 个答案:

答案 0 :(得分:1)

使用Fiddler将您从代码制作的HTTP请求与浏览器制作的HTTP请求进行比较。

为此,请选择两个请求,然后按 CTRL + W (您可能需要按照these instructions配置比较工具)

此外,尝试检查从浏览器发起的所有请求。有些cookie可能是在先前的请求中收到的(通常是您在请求登录页面时发出的GET请求)。如果需要,首先执行GET,收集cookie,然后执行POST。

答案 1 :(得分:0)

<%@ Page Language="C#"%>
<%
for (int i = 0; i < Request.Cookies.Count; i++)
  {
    Response.Write(Request.Cookies[i].Name + " : ");
    Response.Write(Request.Cookies[i].Value);
    Response.Write("<br />");
  }
%>