I have a simple Asp.Net Core
WebApi where I am using HttpClient
to send some custum 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.
There is no need to dispose of the HttpClient instances from HttpClientFactory. Disposal will not actually do anything in this case because the factory manages the handler and connection lifetimes and not the HttpClient instances.
Short answer: use a static HttpClient. If you need to support DNS changes (of your web server or other servers), then you need to worry about timeout settings. It's a testament to how messed up HttpClient is that using it is a "weekend read" as commented by @AnkitVijay.
HttpClient is intended to be instantiated once and reused throughout the life of an application. The following conditions can result in SocketException errors: * Creating a new HttpClient instance per request. * Server under heavy load. Creating a new HttpClient instance per request can exhaust the available sockets.
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With