首页 > 解决方案 > c# 将 CookieContainer 添加到 HttpClientHandler

问题描述

我有以下用 c# 编写的函数:

public static string FunctionName()
{
    try
    {
        using (var httpClient = new HttpClient())
        {
            var uri = new Uri("https://www.website.com/api/1/auth/user");
            httpClient.BaseAddress = uri;
            httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");
            httpClient.DefaultRequestHeaders.Add("Cookie", "apiKey=dasdasd; auth=authcookie_dasd-c28673189043; id_chat.com=dasdasdad");
            return httpClient.GetAsync(uri).Result.ToString();
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message.ToString());
    }

    return null;
}

其中 cookie 直接添加到标题中。现在我试图将其拆分以将其添加到 CookieContainer 中。源代码如下所示:

public static string FunctionName()
{
    try
    {
        HttpClientHandler handler = new HttpClientHandler();
        handler.CookieContainer = new CookieContainer();
        Uri target = new Uri("https://www.website.com");

        handler.CookieContainer.Add(new Cookie("apiKey", "dasdasd") { Domain = target.Host });
        handler.CookieContainer.Add(new Cookie("auth", "authcookie_dasd-c28673189043") { Domain = target.Host }); 
        handler.CookieContainer.Add(new Cookie("id_chat.com", "dasdasdad") { Domain = target.Host });

        HttpClient http = new HttpClient(handler);
        http.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36");

        var response = http.GetAsync("https://www.website.com/api/1/auth/user");

        Console.WriteLine(response.Result.ToString());

        if (response.Result.StatusCode == HttpStatusCode.OK)
        {
            var json = JsonConvert.DeserializeObject<LoginResponse>(response.Result.Content.ReadAsStringAsync().Result);
            return json.id;
        }
    }
    catch (Exception ex) 
    {
        Console.WriteLine(ex.Message.ToString());
    }

    return null;
}

第一个函数将返回状态“OK”。第二个函数将返回状态“未授权”。

是什么导致了这个问题?我是否设置了 CookieContainer 错误?

标签: c#cookiecontainerhttpclienthandler

解决方案


推荐阅读