Dot-Net
使用帶有 .NET 4.5 HttpClient 的代理
我正在解決我通過.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; }然後我通過以下方式發送請求:
var response = CreateHttpClient(ctx, sid).PostAsJsonAsync("api/prefs/", smp).Result;請求直接發送到伺服器而不嘗試訪問代理。我錯過了什麼?
啊,我指向的 BaseAddress 是
http://localhost:8081. 事實證明,儘管將 BypassOnLocal 設置為 false,但顯然 localhost 仍然足夠特殊,可以繞過代理。我在 IIS 中添加了一個域綁定,主機文件條目將該域指向 127.0.0.1,使用新創建的域,現在它可以工作了。
這段程式碼對我有用:
var httpClientHandler = new HttpClientHandler { Proxy = new WebProxy("http://localhost:8888", false), UseProxy = true }請注意,我沒有向
WebProxy建構子提供空數組。也許這就是問題所在?