C# How to pass on a cookie using a shared HttpClie

2019-02-13 16:34发布

问题:

I have the following set up:

JS client -> Web Api -> Web Api

I need to send the auth cookie all the way down. My problem is sending it from one web api to another. Because of integration with an older system, that uses FormsAuthentication, I have to pass on the auth cookie.

For performance reasons I share a list of HttpClients (one for each web api) in the following dictionary:

private static ConcurrentDictionary<ApiIdentifier, HttpClient> _clients = new ConcurrentDictionary<ApiIdentifier, HttpClient>();

So given an identifier I can grab the corresponding HttpClient.

The following works, but I'm pretty sure this is bad code:

HttpClient client = _clients[identifier];
var callerRequest = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage;
string authCookieValue = GetAuthCookieValue(callerRequest);

if (authCookieValue != null)
{
    client.DefaultRequestHeaders.Remove("Cookie");
    client.DefaultRequestHeaders.Add("Cookie", ".ASPXAUTH=" + authCookieValue);
}

HttpResponseMessage response = await client.PutAsJsonAsync(methodName, dataToSend);

// Handle response...

Whats wrong about this is that 1) it seems wrong to manipulate DefaultRequestHeaders in a request and 2) potentially two simultanious requests may mess up the cookies, as the HttpClient is shared.

I've been searching for a while without finding a solution, as most having a matching problem instantiates the HttpClient for every request, hence being able to set the required headers, which I'm trying to avoid.

At one point I had get requests working using a HttpResponseMessage. Perhaps that can be of inspiration to a solution.

So my question is: is there a way to set cookies for a single request using a HttpClient, that will be safe from other clients using the same instance?

回答1:

Instead of calling PutAsJsonAsync() you can use HttpRequestMessage and SendAsync():

Uri requestUri = ...;
HttpMethod method = HttpMethod.Get /*Put, Post, Delete, etc.*/;
var request = new HttpRequestMessage(method, requestUri);
request.Headers.TryAddWithoutValidation("Cookie", ".ASPXAUTH=" + authCookieValue);
request.Content = new StringContent(jsonDataToSend, Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);

UPDATE: To make sure that your HTTP client does not store any cookies from a response you need to do this:

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

Otherwise you might get unexpected behavior by using one client and sharing other cookies.