使用.NET 4.5 HttpClient代理

Mik*_*lin 51 .net .net-4.5 asp.net-web-api

我正在通过.NET的HttpClient调用一个服务错误,尝试通过本地代理(Fiddler)路由请求,但我的代理设置似乎没有生效.

这是我创建客户端的方式:

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;
}
Run Code Online (Sandbox Code Playgroud)

然后我通过以下方式发送请求:

var response = CreateHttpClient(ctx, sid).PostAsJsonAsync("api/prefs/", smp).Result;
Run Code Online (Sandbox Code Playgroud)

请求直接进入服务器而不尝试命中代理.我错过了什么?

Nat*_*nSr 50

这段代码对我有用:

var httpClientHandler = new HttpClientHandler
                        {
                            Proxy = new WebProxy("http://localhost:8888", false),
                            UseProxy = true
                        }
Run Code Online (Sandbox Code Playgroud)

请注意,我没有向WebProxy构造函数提供空数组.也许那就是问题?


Mik*_*lin 7

啊,我指的是BaseAddress http://localhost:8081.事实证明,尽管将BypassOnLocal设置为false,显然localhost仍然很特别,它绕过了代理.

我在IIS中添加了一个域绑定,主机文件条目将该域指向127.0.0.1,使用了新创建的域,现在它可以工作了.

  • 我收到了错误的请求 - 无效的主机名.在localhost之后 (2认同)