使用代理与.NET 4.5的HttpClient

使用代理与.NET 4.5的HttpClient

问题描述:

我的故障排除与我通过.NET的HttpClient的呼吁,试图借道本地代理(小提琴手)请求服务的错误,但我的代理服务器设置似乎不生效。

I'm troubleshooting a bug with a service I call through .NET's HttpClient, trying to route the request through a local proxy (Fiddler), but my proxy settings seem to not be taking effect.

下面是我如何创建客户端:

Here's how I create the client:

    private HttpClient CreateHttpClient(CommandContext ctx, string sid) {
        var cookies = new CookieContainer();

        var handler = new HttpClientHandler {
            CookieContainer = cookies,
            UseCookies = true,
            UseDefaultCredentials = false,
            Proxy = new WebProxy("http://localhost:8888", false, new string[]{}),
            UseProxy = true,
        };

        // snip out some irrelevant setting of authentication cookies

        var client = new HttpClient(handler) {
            BaseAddress = _prefServerBaseUrl,
        };

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        return client;
    }

然后,我通过发送请求:

then I send the request by:

        var response = CreateHttpClient(ctx, sid).PostAsJsonAsync("api/prefs/", smp).Result;

要求去直接到服务器,而不是试图打代理。我错过了什么?

Request goes straight to the server without attempting to hit the proxy. What did I miss?

嗯,我指着BaseAddress是的http://本地主机:8081 。事实证明,尽管设置BypassOnLocal为false,看样子本地主机仍然是够特别,它绕过代理。

Ah, The BaseAddress I was pointing to was http://localhost:8081. Turns out that despite setting BypassOnLocal to false, evidently localhost is still special enough that it bypasses the proxy.

我添加了一个域名在IIS中,主机文件条目结合指向该​​域为127.0.0.1,使用新创建的域,现在它的工作原理。

I added a domain binding in IIS, host file entry to point that domain to 127.0.0.1, used newly created domain, now it works.