如何在c#中检索所有cookie

本文关键字:cookie 检索 | 更新日期: 2023-09-27 18:26:06

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

问题是,当我在fiddler中检查我的程序响应时,有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

为什么我的请求中有一个"$"字符?

如何在c#中检索所有cookie

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

要执行此操作,请选择两个请求,然后按CTRL+W(您可能必须按照以下说明配置比较工具)

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

<%@ 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 />");
  }
%>