Search code examples
c#asp.net-corecookiesdotnet-httpclient

Is it possible to configure HttpClient not to save cookies?


I have a simple Asp.Net Core WebApi where I am using HttpClient to send some custom web requests. I am using HttpClient like so:

services.AddHttpClient<IMyInterface, MyService>()
...

public class MyService : IMyInterface
{
    private readonly HttpClient _client;

    public MyService(HttpClient client)
    {
        _client = client;
    } 

    public async Task SendWebRequest()
    {
        var url = "https://MyCustomUrl.com/myCustomResource";
        var request = new HttpRequestMessage(HttpMethod.Get, url);
        var response = await _client.SendAsync(request);
        ...
    }
}   

I have noticed that when I send multiple requests, HttpClient saves cookies which it received with first response in Set-Cookie header. It adds those cookies to consecutive request headers. (I have inspected this with fiddler). Flow:

//First requst
GET https://MyCustomUrl.com/myCustomResource HTTP/1.1

//First response
HTTP/1.1 200 OK
Set-Cookie: key=value
...

//Second request
GET https://MyCustomUrl.com/myCustomResource HTTP/1.1
Cookie: key=value

//Second response
HTTP/1.1 200 OK
...

Is there a way to force HttpClient not to add cookies?

This happens only in the same session, so if I would dispose HttpClient then cookies would not be added. But disposing HttpClient might bring some other issues.


Solution

  • See HttpClientHandler.UseCookies.

    Gets or sets a value that indicates whether the handler uses the CookieContainer property to store server cookies and uses these cookies when sending requests.

    So you'll need to do:

    var handler = new HttpClientHandler() { UseCookies = false };
    var httpClient = new HttpClient(handler);
    

    If you're using HttpClientFactory in asp.net core, then this answer suggests that the way to do this is:

    services.AddHttpClient("configured-inner-handler")
        .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler() { UseCookies = false });