根据请求设置' cookie .Net HttpClient

时间:2016-11-25 15:07:37

标签: c# cookies owin dotnet-httpclient

您好我尝试使用Owin基础架构实现简单的http代理服务。此代理必须使用Windows身份验证对用户进行身份验证,从企业AD中提取用户属性,将此信息作为cookie值添加到原始请求中,然后将请求重定向到Internet上的应用程序(我们称之为外部应用程序)。 / p>

我正在使用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     {         private readonly 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)
    }
}

1 个答案:

答案 0 :(得分:1)

在此处找到解决方案:enter link description here 诀窍在于明确将HttpClientHandler的UseCookie标志设置为 false

var handler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Automatic, UseCookie = false };