您好我正在嘗試使用Owin基礎設施來實現簡單的http代理服務。此代理必須使用Windows身份驗證對用戶進行身份驗證,從企業AD中提取用戶屬性,將此信息作爲cookie值添加到原始請求中,然後將請求重定向到Internet上的應用程序(稱爲「外部應用程序」)。用.Net HttpClient設置'每個請求'的cookie
我正在使用HttpClient向外部應用程序發送請求。
但是HttpClient不適合這種情況。似乎唯一允許的使用cookie的方式是將它們放入CookieContainer中,並將此CookieContainer設置爲HttpClientHandler的屬性。當你有單一用戶時沒關係,但如果是代理服務,來自不同用戶的cookie值將會混合並相互覆蓋。
是否有任何方法可以爲每個請求設置Cookie或CookieContainer?或者,也許有更好的方式來重定向請求?
P.S.下面是一些代碼:
初始化HTTP處理的:
private void RegisterRoutes(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Proxy",
routeTemplate: "{*path}",
handler: HttpClientFactory.CreatePipeline
(
innerHandler: new HttpClientHandler(),
handlers: new DelegatingHandler[]
{
new ProxyHandler()
}
),
defaults: new { path = RouteParameter.Optional },
constraints: null);
}
ProxyHandler 內部類ProxyHandler:DelegatingHandler { 私人只讀HttpClient的_client;
public ProxyHandler()
{
var handler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Automatic};
_client = new HttpClient(handler);
}
protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var forwardUri = new UriBuilder(request.RequestUri);
forwardUri.Host = "localhost";
forwardUri.Port = 23016;
forwardUri.Scheme = Uri.UriSchemeHttp;
request.RequestUri = forwardUri.Uri;
request.Headers.Host = forwardUri.Host;
//Explicitly null it to avoid protocol violation
if (request.Method == HttpMethod.Get || request.Method == HttpMethod.Trace)
request.Content = null;
try
{
var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
//Explicitly null it to avoid protocol violation
if (request.Method == HttpMethod.Head)
response.Content = null;
return response;
}
catch (Exception ex)
{
var response = request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
string message = ex.Message;
if (ex.InnerException != null)
message += ':' + ex.InnerException.Message;
response.Content = new StringContent(message);
Trace.TraceError("Error:{0}", message);
return response;
}
}
private void SetCookies(HttpRequestMessage request)
{
var container = new CookieContainer();
var authCookieValue = "2EF91D8FD9EDC594F2DB82";
var authCookie = new Cookie("cookieByProxy", authCookieValue);
var targetUri = new Uri("http://localhost:23016/");
container.Add(targetUri, authCookie);
var cookieHeader = container.GetCookieHeader(targetUri);
if (!string.IsNullOrEmpty(cookieHeader))
request.Headers.TryAddWithoutValidation("Cookie", cookieHeader);//Overwriting cookie header with custom values. However cookie values are ignored by HttpClient (both old and new)
}
}
謝謝你的建議,但我實際上期待高流量。 –