Issue with CookieContainer when use HttpClientFactory
See original GitHub issueDescribe the bug
HttpClient
objects which are created from HttpClientFactory
may use the same pooled HttpClientHandler
object, so they may use the same CookieContainer
object. This causes a thread-safe issue.
To Reproduce
Assume we have a web application call to api/Token (GET) of API server.
Web:
public async Task<string> GetToken()
{
var httpClient = _clientFactory.CreateClient();
var response = await httpClient.GetAsync("http://api.local:5089/api/token");
var token = await response.Content.ReadAsStringAsync();
return token;
}
API:
public ActionResult<string> Get()
{
string token = HttpContext.Request.Cookies.ContainsKey("Token") ?
HttpContext.Request.Cookies["Token"] : Guid.NewGuid().ToString();
HttpContext.Response.Cookies.Append("Token", token);
return token;
}
Step 1: Make the first request to API, in Web application, response.Headers.GetValues("Set-Cookies")
will show “Token” cookie’s value equals “abc”
Step 2: Make a second request to API, in Web application, response.Headers.GetValues("Set-Cookies")
will show “Token” cookie’s value also equals “abc”
Expected behavior
HttpClient
objects which are created by HttpClientFactory
should have the same behavior as creating new HttpClient
If we use new HttpClient()
, each request to API, we will get new Token value, but we cannot achieve this
purpose with HttpClientFatory
. How could we deal with this problem when we have to use Cookie in API?
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:6 (2 by maintainers)
Top GitHub Comments
You can configure the underlying
HttpMessageHandler
to not use a cookie container, which means you have to handle the cookies yourself from the headers.Closing this, I’ve created an issue and PR on the docs repo.