Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

asp.net web api - Using a proxy with .NET 4.5 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This code worked for me:

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

Note that I am not supplying an empty array to my WebProxy constructor. Perhaps that's the problem?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...