Struggling trying to get cookie out of response with HttpClient in .net 4.5

后端 未结 3 596
自闭症患者
自闭症患者 2020-11-28 20:03

I\'ve got the following code that works successfully. I can\'t figure out how to get the cookie out of the response. My goal is that I want to be able to set cookies in th

3条回答
  •  迷失自我
    2020-11-28 20:29

    There's alternative if you don't have access to the HttpClient and can't inject the CookieContainer. This works in .NET Core 2.2:

    private string GetCookie(HttpResponseMessage message)
    {
        message.Headers.TryGetValues("Set-Cookie", out var setCookie);
        var setCookieString = setCookie.Single();
        var cookieTokens = setCookieString.Split(';');
        var firstCookie = cookieTokens.FirstOrDefault();
        var keyValueTokens = firstCookie.Split('=');
        var valueString = keyValueTokens[1];
        var cookieValue = HttpUtility.UrlDecode(valueString);
        return cookieValue;
    }
    

提交回复
热议问题