我进行了以下设置:
JS 客户端 -> Web Api -> Web Api
我需要将身份验证 cookie 一路向下发送。我的问题是将其从一个 Web api 发送到另一个。由于与使用 FormsAuthentication 的旧系统集成,我必须传递身份验证 cookie。
出于性能原因,我在以下字典中共享 HttpClient 列表(每个 Web api 一个):
private static ConcurrentDictionary<ApiIdentifier, HttpClient> _clients = new ConcurrentDictionary<ApiIdentifier, HttpClient>();
因此,给定一个标识符,我可以获取相应的 HttpClient。
以下有效,但我很确定这是错误的代码:
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...
问题在于 1)操纵似乎是错误的DefaultRequestHeaders
在一个请求中,2) 两个同时发生的请求可能会弄乱 cookie,因为 HttpClient 是共享的。
我已经搜索了一段时间但没有找到解决方案,因为大多数遇到匹配问题的人都会为每个请求实例化 HttpClient,因此能够设置所需的标头,这是我试图避免的。
有一次我收到了使用以下命令工作的请求HttpResponseMessage
。也许这可以为解决方案提供灵感。
所以我的问题是:有没有一种方法可以使用 HttpClient 为单个请求设置 cookie,这样对于使用同一实例的其他客户端来说是安全的?