问题描述
我正在解决我通过 .NET 的 HttpClient 调用的服务的错误,尝试通过本地代理 (Fiddler) 路由请求,但我的代理设置似乎没有生效.
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://localhost:8081
.事实证明,尽管将 BypassOnLocal 设置为 false,但显然 localhost 仍然足够特殊,可以绕过代理.
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.
这篇关于在 .NET 4.5 HttpClient 中使用代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!