简体   繁体   English

C# HttpClient - 如果在请求标头中将 UseCookies 设置为 false,是否可以从响应中获取 cookie?

[英]C# HttpClient - Is it possible to get cookies from the response if UseCookies is set to false in the request header?

I know you can get cookies by adding a CookieContainer in the request handler.我知道您可以通过在请求处理程序中添加 CookieContainer 来获取 cookie。

However, the following post request fails unless I set UseCookies to false:但是,除非我将 UseCookies 设置为 false,否则以下发布请求将失败:

static CookieContainer cookies = new CookieContainer();    

  var clientHandler = new HttpClientHandler
    {
       //Original Apporach - this fails the POST request 
       // UseCookies = true,
       // CookieContainer = cookies,

       //I had to do this
        UseCookies = false,
    };
    var client = new HttpClient(clientHandler);
    var request = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        RequestUri = new Uri("*redacted*"),
        Headers =
        {
            { "cookie", "SampleCookie" },
        },
        Content = new FormUrlEncodedContent(new Dictionary<string, string>
        {
            { "Provider", "Email" },
            { "Code", "12345" },
            { "RememberMe", "False" },
            { "RememberBrowser", "false" },
            { "__RequestVerificationToken", "SampleToken" },
        }),
    };
    using (var response = await client.SendAsync(request))
    {
        response.EnsureSuccessStatusCode();
        var body = await response.Content.ReadAsStringAsync();
        Console.WriteLine(body);
    }

Not very knowledgeable with HTTP request to be honest.老实说,对 HTTP 请求不是很了解。 Is my original approach failing because I'm setting the cookie manually?我的原始方法是否因为我手动设置 cookie 而失败?

The reason for the request failing might depend on many things - like authentication and other headers needed, without knowing the specifics of what you're trying to access it's hard to tell what's causing it.请求失败的原因可能取决于很多事情——比如身份验证和需要的其他标头,如果不知道您尝试访问的具体内容,就很难说出是什么原因造成的。 Here's a simple example that shows how to make a request to Google front page and get all the cookies into the container and print them out in a Console app:这是一个简单的示例,展示了如何向 Google 首页发出请求并将所有 cookie 获取到容器中并在控制台应用程序中打印出来:

static void Main(string[] args)
{
    var uri = new Uri("https://google.com");
    var cookies = new CookieContainer();
    var handler = new HttpClientHandler();
    handler.CookieContainer = cookies;

    using (var client = new HttpClient(handler))
    {
        var result = client.GetAsync(uri).Result;
    }

    foreach (Cookie cookie in cookies.GetCookies(uri))
    {
        var print = $"cookie name: {cookie.Name}\ncookie value: {cookie.Value}\n";
        Console.WriteLine(print);
    }
}

many people still recommend UseCookies = false to send/override custom cookies, this is wrong.许多人仍然建议UseCookies = false发送/覆盖自定义 cookie,这是错误的。

UseCookies = false is to disable request/response cookies container, I know if I do this I can send custom header Cookie but the downside I cannot read Response Cookie inside cookie container or even response headers. UseCookies = false是禁用请求/响应 cookie 容器,我知道如果这样做,我可以发送自定义标头Cookie ,但缺点是我无法读取 cookie 容器内的Response Cookie ,甚至无法读取响应标头。

The right way to override this, is to set the cookie inside the CookieContainer覆盖它的正确方法是在CookieContainer中设置 cookie

CookieContainer cookies = new CookieContainer();
// add your custom cookie here
Cookie customCookie = new Cookie("cookieKey", "cookieValue" "/", "example.com");
cookies.Add(customCookie);

var clientHandler = new HttpClientHandler
{
    CookieContainer = cookies,
    //UseCookies = false, // no need this
};

// no need to write
// Headers = { { "cookie", "cookieKey=cookieValue" } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM