こんにちは私はOwinインフラストラクチャを使用して簡単なHTTPプロキシサービスを実装しようとしています。このプロキシは、Windows認証を使用してユーザーを認証し、エンタープライズADからユーザーのプロパティを取得し、この情報をCookie値として元の要求に追加し、インターネット上のアプリケーションに要求をリダイレクトする必要があります。.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)
}
}
あなたのご提案ありがとうございますが、私は実際には高いトラフィックを期待しています。 –