4

I'm trying to specify the web proxy for a request using WebAPI in a dotnet core app. This block of code used to work when I targeted the actual clr (dnx46) but, now I'm trying to use the rc2 stuff that says the supported frameworks are netcoreapp1.0 and netstandard1.5.

var clientHandler = new HttpClientHandler{
    Proxy = string.IsNullOrWhiteSpace(this._clientSettings.ProxyUrl) ? null : new WebProxy (this._clientSettings.ProxyUrl, this._clientSettings.BypassProxyOnLocal),
    UseProxy = !string.IsNullOrWhiteSpace(this._clientSettings.ProxyUrl)
};

I'm wondering where WebProxy class went. I can't find it anywhere, not even in the github repositories. If it changed from WebProxy, what did it change to? I need to be able to set the proxy to a specific url for specific requests, so using the "global Internet Explorer" way of things isn't going to work for my needs. This is mostly for debugging of web requests/response purposes.

1 Answer 1

6

Ran into the same issue today. Turns out that we have to provide our own implementation of IWebProxy. Fortunately it's not complicated at all:

public class MyProxy : IWebProxy
{
    public MyProxy(string proxyUri)
        : this(new Uri(proxyUri))
    {
    }

    public MyProxy(Uri proxyUri)
    {
        this.ProxyUri = proxyUri;
    }

    public Uri ProxyUri { get; set; }

    public ICredentials Credentials { get; set; }

    public Uri GetProxy(Uri destination)
    {
        return this.ProxyUri;
    }

    public bool IsBypassed(Uri host)
    {
        return false; /* Proxy all requests */
    }
}

And you would use it like this:

var config = new HttpClientHandler
{
    UseProxy = true,
    Proxy = new MyProxy("http://127.0.0.1:8118")
};

using (var http = new HttpClient(config))
{
    var ip = http.GetStringAsync("https://api.ipify.org/").Result;

    Console.WriteLine("Your IP: {0}");
}

And in your particular situation you could even put the logic determining if a proxy is required inside your IWebProxy implementation.

Sign up to request clarification or add additional context in comments.

2 Comments

I've faced similar issue but with one difference. I need to use default system proxy. However for .net framework setting proxy to null does work. Please correct if i'm wrong.
How make .net core to use default system proxy?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.