在 asp.net core rc2 中指定代理

Posted

技术标签:

【中文标题】在 asp.net core rc2 中指定代理【英文标题】:Specify proxy in asp.net core rc2 【发布时间】:2016-05-17 00:44:53 【问题描述】:

我正在尝试在 dotnet 核心应用程序中使用 WebAPI 为请求指定 Web 代理。当我针对实际的 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】:

今天遇到了同样的问题。事实证明,我们必须提供自己的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 确实有效。如果我错了,请纠正。 如何让.net core使用默认系统代理?

以上是关于在 asp.net core rc2 中指定代理的主要内容,如果未能解决你的问题,请参考以下文章