1

I have the following function written in 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;
}

where the cookie is added directly to the header. Now I was trying to split this up to add it to a CookieContainer. The source code looks like the following:

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;
}

The first function would return the status "OK". The second function would return the status "Unauthorized".

What is causing this problem? Did I set up the CookieContainer wrong?

pr0b
  • 377
  • 2
  • 3
  • 14

0 Answers0