标签: cookiecontainer

CookieContainer处理路径(谁吃了我的cookie?)

我正在开发一个涉及一些基本网络爬行的项目.我已经非常成功地使用HttpWebRequest和HttpWebResponse.对于cookie处理,我只有一个CookieContainer,我每次都分配给HttpWebRequest.CookieContainer.每次我自动填充新的cookie,不需要我的额外处理.直到不久之前,当其中一个曾经工作的网站突然停止工作时,这一切都很好.我有理由相信这是一个有问题的cookie,但是我没有保留过去工作时的cookie记录,所以我不是100%肯定.

我用以下代码设法模拟了这个问题:

CookieContainer cookieJar = new CookieContainer();

Uri uri1 = new Uri("http://www.somedomain.com/some/path/page1.html");
CookieCollection cookies1 = new CookieCollection();
cookies1.Add(new Cookie("NoPathCookie", "Page1Value"));
cookies1.Add(new Cookie("CookieWithPath", "Page1Value", "/some/path/"));

Uri uri2 = new Uri("http://www.somedomain.com/some/path/page2.html");
CookieCollection cookies2 = new CookieCollection();
cookies2.Add(new Cookie("NoPathCookie", "Page2Value"));
cookies2.Add(new Cookie("CookieWithPath", "Page2Value", "/some/path/"));

Uri uri3 = new Uri("http://www.somedomain.com/some/path/page3.html");

// Add the cookies from page1.html
cookieJar.Add(uri1, cookies1);

// Add the cookies from page2.html
cookieJar.Add(uri2, cookies2);

// We should now have 3 cookies
Console.WriteLine(string.Format("CookieJar contains {0} cookies", cookieJar.Count));

Console.WriteLine(string.Format("Cookies to send to page1.html: {0}", …
Run Code Online (Sandbox Code Playgroud)

.net c# cookies httpwebrequest cookiecontainer

9
推荐指数
1
解决办法
2193
查看次数

HttpWebRequest.Headers.Add("Cookie",value)vs HttpWebRequest.CookieContainer

当我得到响应HttpWebRequestHttpWebRequest.Headers.Add("Cookie",value)VS HttpWebRequest.CookieContainer,和结果的差异.

那么,它们之间有什么区别,何时使用它们.

c# cookies httpwebrequest cookiecontainer http-headers

8
推荐指数
1
解决办法
7987
查看次数

在WPF WebBrowser控件中管理cookie?

有没有办法读取/写入WebBrowser控件使用的cookie?

我正在做这样的事......

string resultHtml;
HttpWebRequest request = CreateMyHttpWebRequest(); // fills http headers and stuff
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
    resultHtml = sr.ReadToEnd();
}
WebBrowser browser = new WebBrowser();
browser.CookieContainer = request.CookieContainer; // i wish i could do this :(
browser.NavigateToString(resultHtml);  
Run Code Online (Sandbox Code Playgroud)

browser cookies wpf httpwebrequest cookiecontainer

7
推荐指数
2
解决办法
1万
查看次数

带有类型化客户端的 cookieContainer

需要向需要特定cookie的服务器发出请求。能够使用 HTTP 客户端和带有 cookiecontainer 的处理程序来完成此操作。通过使用类型化客户端,无法找到设置 cookiecontainer 的方法。

使用http客户端:

var cookieContainer = new CookieContainer();
using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
using (HttpClient client = new HttpClient(handler))
{
    //.....

    // Used below method to add cookies
    AddCookies(cookieContainer);

    var response = client.GetAsync('/').Result;
} 
Run Code Online (Sandbox Code Playgroud)

使用 HttpClientFactory:

在startup.cs中

services.AddHttpClient<TypedClient>().
           ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
           {
               CookieContainer = new CookieContainer()
            });
Run Code Online (Sandbox Code Playgroud)

在控制器类中

// Need to call AddCookie method here
var response =_typedclient.client.GetAsync('/').Result;
Run Code Online (Sandbox Code Playgroud)

在 Addcookie 方法中,我需要将 cookie 添加到容器中。任何建议如何做到这一点。

c# cookiecontainer dotnet-httpclient .net-core httpclientfactory

7
推荐指数
1
解决办法
936
查看次数

使用CookieContainer的WCF Web服务客户端

我开发了一个小型C#表单应用程序,它调用Web服务.一切都运行良好,但我需要保持状态,并且如果我没有记错,我需要使用CookieContainer.

我使用项目的"添加服务引用"菜单创建了服务引用,一切运行良好.但我不知道如何在创建的客户端上添加CookieManager.

我发现一些示例显示样本:

serviceClient.CookieContainer=new CookieContainer()
Run Code Online (Sandbox Code Playgroud)

但这种情况并非如此.我的服务客户端没有这样的属性.我顺便提起Visual Studio 2010 Beta.

先感谢您!

这是生成的ServiceReference(自动创建):

//------------------------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

// //此代码由工具生成.//运行时版本:4.0.30128.1 // //对此文件的更改可能会导致错误的行为,如果//重新生成代码,则会丢失.// // ---------------------------------------------- --------------------------------

namespace WSClient.SecurityServiceReference {

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://max/", ConfigurationName="SecurityServiceReference.SecurityService")]
public interface SecurityService {

    // CODEGEN: Generating message contract since element name return from namespace  is not marked nillable
    [System.ServiceModel.OperationContractAttribute(Action="http://max/SecurityService/nextValRequest", ReplyAction="http://max/SecurityService/nextValResponse")]
    [System.ServiceModel.TransactionFlowAttribute(System.ServiceModel.TransactionFlowOption.Allowed)]
    WSClient.SecurityServiceReference.nextValResponse nextVal(WSClient.SecurityServiceReference.nextValRequest request);

    // CODEGEN: Generating message contract since element name return from namespace  is not marked nillable
    [System.ServiceModel.OperationContractAttribute(Action="http://max/SecurityService/reportSessionIDRequest", ReplyAction="http://max/SecurityService/reportSessionIDResponse")]
    [System.ServiceModel.TransactionFlowAttribute(System.ServiceModel.TransactionFlowOption.Allowed)]
    WSClient.SecurityServiceReference.reportSessionIDResponse reportSessionID(WSClient.SecurityServiceReference.reportSessionIDRequest request);
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(IsWrapped=false)]
public partial …
Run Code Online (Sandbox Code Playgroud)

c# cookies wcf web-services cookiecontainer

6
推荐指数
2
解决办法
1万
查看次数

在Windows Phone 7(Mango)上的HttpWebRequests之间共享CookieContainer的问题

我有一个生产应用程序通过HttpWebRequest进行两次调用.第一个调用设置会话并接收cookie以维持会话,第二个调用是来自api的数据.回复是httponly.我在两个调用之间使用共享CookieContainer,但第二个调用总是失败.我将问题缩小到第二个请求中没有发送的cookie.我已经使用网络监视器来监视流量,如果我在第二个请求中明确设置了cookie(参见下面的代码),则呼叫成功.有人对这个问题有任何想法吗?我需要弄清楚如何使用共享的CookieContainer.

private string URL_01 = "https:// [...]";
private string URL_02 = "https:// [...]";
private CookieContainer _cookieContainer = new CookieContainer();
private NetworkCredential nc = new NetworkCredential("username", "password");

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
HttpWebRequest request = HttpWebRequest.CreateHttp(URL_01);
request.CookieContainer = _cookieContainer;
request.Credentials = nc;
request.UseDefaultCredentials = false;
request.BeginGetResponse(new AsyncCallback(HandleResponse), request);
}

public void HandleResponse(IAsyncResult result)
{
HttpWebRequest request = result.AsyncState as HttpWebRequest;

if (request != null)
{
    using (WebResponse response = request.EndGetResponse(result))
    {
         using (StreamReader reader = new StreamReader(response.GetResponseStream()))
         {
             string …
Run Code Online (Sandbox Code Playgroud)

cookiecontainer windows-phone-7 windows-phone-7.1

5
推荐指数
1
解决办法
2700
查看次数

CookieContainer混乱

据我所知,CookieContainer通过HttpWebRequests持久化Cookie的基本用法如下:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
CookieContainer cookies = new CookieContainer();
request.CookieContainer = cookies;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
  // Do stuff with response
}
Run Code Online (Sandbox Code Playgroud)

然后:

request = (HttpWebRequest)WebRequest.Create(new url);
request.CookieContainer = cookies;
etc...
Run Code Online (Sandbox Code Playgroud)

但我无法理解这个过程背后的逻辑.变量cookie在初始化后似乎没有被重新分配.第一个WebResponse的cookie到底是如何进入第二个WebRequest的?

c# session httpwebrequest cookiecontainer

5
推荐指数
1
解决办法
1万
查看次数

使.NET WebBrowser不与IE或其他实例共享cookie

由于C#中的WebBrowser与包括IE在内的所有其他WebBrowsers实例共享cookie,我希望WebBrowser拥有自己的cookie容器,该容器不共享之前在IE或其他实例中创建的任何cookie.

因此,例如,当我创建WebBrowser时,它不应该有任何cookie.当我运行2个WebBrowsers实例时,它们拥有自己的cookie容器,并且不会彼此共享或冲突cookie.

我怎样才能做到这一点?

.net c# browser cookies cookiecontainer

5
推荐指数
1
解决办法
3363
查看次数

严重的CookieContainer错误?

我在这里遗漏了什么,或者这是CookieContainer中的错误?

我正在向容器中添加3个cookie,然后我为2个URL调用GetCookieHeader函数:

CookieContainer cc = new CookieContainer();

cc.Add(new Cookie("Cookie1", "1", "/a", "test.com"));
cc.Add(new Cookie("Cookie2", "2", "/a/0/", "test.com"));
cc.Add(new Cookie("Cookie3", "3", "/a/1/", "test.com"));

var result1 = cc.GetCookieHeader(new Uri("http://test.com/a/1/list"));
Assert.AreEqual("Cookie3=3; Cookie1=1", result1);

var result2 = cc.GetCookieHeader(new Uri("http://test.com/a/0/list"));
Assert.AreEqual("Cookie2=2; Cookie1=1", result2);
Run Code Online (Sandbox Code Playgroud)

问题是抛出异常的最后一个断言,因为返回的头只是"Cookie2 = 2".我没有看到为什么在那里省略Cookie1 cookie的原因 - 根据RFC6265它应该返回两个类似于上面第一个断言的cookie,不应该吗?

几句话:

  • cookie都在容器中,因此不是添加问题而是GetHeader函数.

  • 添加4,5等cookie时,此行为保持不变:只有与最后添加的cookie匹配的路径才会包含基本路径的cookie!

  • 删除路径中的所有"a"并仅使用"/","/ 0 /"和"/ 1 /"作为3个cookie的路径和" http://test.com/1/list " 时,行为会发生变化断言网址中的" http://test.com/0/list ").所有断言然后成功 - 我期望与"a"相同的行为!

PS:让我从规范中添加相关部分:

如果至少满足下列条件之一,请求路径路径将匹配给定的cookie路径:

- cookie路径和请求路径是相同的.

- cookie-path是请求路径的前缀,cookie路径的最后一个字符是%x2F("/").

- cookie-path是请求路径的前缀,而cookie路径中未包含的请求路径的第一个字符是%x2F("/")字符.

所以对我来说这显然是一个错误......?

c# system.net cookiecontainer web

5
推荐指数
1
解决办法
277
查看次数

无法使用 C# HttpClient 获取任何 cookie

我正在尝试使用 C# 和 HttpClient 类在 Spotify 登录页面上获取 cookie。但是,当我知道正在设置 cookie 时,CookieContainer 始终为空。我没有发送任何标头,但它仍然应该给我 cookie(s) 因为当我发送一个没有任何标头的 GET 请求时,我得到了 csrf 令牌。这是我的代码:

using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;
using System.Web;

class Program
{
    static void Main()
    {
        Task t = new Task(MakeRequest);
        t.Start();
        Console.WriteLine("Getting cookies!");
        Console.ReadLine();
    }

    static async void MakeRequest()
    {
        CookieContainer cookies = new CookieContainer();
        HttpClientHandler handler = new HttpClientHandler();

        handler.CookieContainer = cookies;
        Uri uri = new Uri("https://accounts.spotify.com/en/login/?_locale=en-US&continue=https:%2F%2Fwww.spotify.com%2Fus%2Faccount%2Foverview%2F");
        HttpClient client = new HttpClient(handler); …
Run Code Online (Sandbox Code Playgroud)

c# cookies cookiecontainer spotify dotnet-httpclient

5
推荐指数
2
解决办法
8059
查看次数

httpwebrequest Cookiecontainer

如何使用"/"以外的路径处理cookie.HttpWebRequest对象返回以下标头:

HTTP/1.1 302 Moved Temporarily
Transfer-Encoding: chunked
Date: Wed, 10 Jun 2009 13:22:53 GMT
Content-Type: text/html; charset=UTF-8
Expires: Wed, 10 Jun 2009 13:22:53 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Server: nginx/0.7.41
X-Powered-By: PHP/5.2.9
Last-Modified: Wed, 10 Jun 2009 13:22:52 GMT
Pragma: no-cache
Set-Cookie: cookie1=c1; path=/; domain=site.com
Set-Cookie: cookie2=c2; path=/content; domain=site.com; httponly
Set-Cookie: cookie3=c3; path=/admin; domain=site.com; httponly
Set-Cookie: cookie4=c4; path=/; domain=site.com; httponly
Location: http://site.com/admin/
Via: 1.1 mvo-netcache-02 (NetCache NetApp/6.0.7)
Run Code Online (Sandbox Code Playgroud)

迭代cookie集合只包含路径为"/"的cookie.因此cookiecontainer中只包含cookie1和cookie4.

为什么没有收集剩下的?如何使用"/"以外的路径访问cookie?我可以将它们全部收集在一个容器中吗?

谢谢

.net path httpwebrequest cookiecontainer

4
推荐指数
1
解决办法
6321
查看次数

通过 .NET 中的 Web 服务调用发送 cookie

我在 .NET 中将 cookie 设置为 Web 服务调用时遇到问题。在使用提供的 wsdl 的任何调用之前,我必须提供一个在登录到客户网站时获得的 cookie。我有一个方法来登录和检索 cookie,然后我将它传递给我的 makeSearch 方法(如下所示)。如您所见,我正在 cookieContainer 中为 wsdl 对象设置 cookie;但是,当我检查 AdvancedSearch 方法发出的请求时,我注意到 fiddler 没有发送 cookie。客户端用 Java 提供了解决方案,但在将其传输到 .NET 时遇到了问题。

以下是Java代码中的解决方法:(port为传入的wsdl对象)

private static void setupClient(Object port, final String cookie) throws Exception {
    Client client = ClientProxy.getClient(port); 
    HTTPConduit http = (HTTPConduit) client.getConduit();
    HTTPClientPolicy policy = http.getClient();
    if (policy == null) {
        policy = new HTTPClientPolicy();
        http.setClient(policy);
    }
    policy.setCookie(cookie);
    policy.setAutoRedirect(true);
}
Run Code Online (Sandbox Code Playgroud)

我的代码如下:

public AdvancedSearchResult makeSearch(String cookie) {
    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
    AdvancedSearchResult searchResults = new AdvancedSearchResult(); …
Run Code Online (Sandbox Code Playgroud)

.net soap web-services cookiecontainer

4
推荐指数
1
解决办法
7632
查看次数