Using cookies with HttpClient

This simple code snippet shows how to store and use cookies from a web request using the .Net HttpClient. For example, if an API or site sends a token or authentication cookie, you may need to store it and send it on all subsequent requests to show that you are authenticated. This would be for a session-based service. The key is to create a single CookieContainer instance and a single HttpClientHandler instance to hold it. Assume the following class is registered as a singleton.

public class WebClient
{
    private CookieContainer _cookieContainer;
    private HttpClientHandler _handler;
 
    private HttpClientHandler Handler
    {
        get
        {
            if (_handler == null)
            {
                _cookieContainer = new CookieContainer();
                _handler = new HttpClientHandler { CookieContainer = _cookieContainer, UseCookies = true, AllowAutoRedirect = false };
            }
            return _handler;
        }
    }
 
    private HttpClient GetClient()
    {
        // the second param prevents the Handler from being disposed with the client
        var client = new HttpClient(Handler, false);
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        return client;
    }
 
    public async Task Get<T>(string path) where T : class
    {
        using (var client = GetClient())
        {
            var content = await client.GetStringAsync(path);
            return JsonConvert.DeserializeObject<T>(content);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

*