在 asp.net core rc2 中指定代理

4

我正在尝试使用WebAPI在dotnet core应用程序中指定网络代理。这段代码在我针对实际的clr(dnx46)时曾经可用,但现在我正在尝试使用rc2的东西,该版本支持的框架是netcoreapp1.0和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)
};

我想知道WebProxy类去哪了。我无法在任何地方找到它,甚至在github存储库中也找不到。如果从WebProxy更改了什么,那它改为了什么? 我需要能够为特定请求设置代理到特定的url,因此使用“全局Internet Explorer”的方式对我的需求没有用。这主要是用于调试Web请求/响应目的。

1个回答

6
今天遇到了同样的问题。原来我们需要提供自己的IWebProxy实现。幸运的是,这并不复杂:
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 */
    }
}

您可以像这样使用它:

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}");
}

在您的特定情况下,甚至可以将确定是否需要代理的逻辑放置在您的IWebProxy实现中。


我遇到了类似的问题,但有一个区别。我需要使用默认系统代理。然而,在.net框架中将代理设置为null是无效的。请纠正我如果我错了。 - neleus
如何让 .NET Core 使用默认系统代理? - coolcake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接