Azure Blob 存储客户端库 v12 设置代理

Azure Blob Storage client library v12 setting proxy

我从 v11 迁移到 v12,我想替换 :

var c = new CloudBlobClient(credentiels, delegatingHandler);

var c = new BlobServiceClient(uri, credentiels);

问题是如何在 v12 中传递 delegatingHandler

v12 azure.Storage.Blobs class name is different from v11. v12 has no DelegatingHandler parameter in the constructor.

DelegatingHandler 可以更改 HttpClientHandler 的 Proxy 属性。

  • 在这种情况下,此实例对于客户端将是唯一的。如果您不指定 DelegatingHandler,将使用单例 HttpClientHandler。
  • 如前所述,我们使用 DelegatingHandler,它具有更改 Proxy 属性的能力。首先,我们将为此构建一个 DelegatingHandler 实现。

ProxyInjectionHandler.cs

using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace Hoge {
  public class ProxyInjectionHandler: DelegatingHandler {
    private readonly IWebProxy Proxy;
    private bool FirstCall = true;

    public ProxyInjectionHandler(IWebProxy proxy) {
      this.Proxy = proxy;
    }

    protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
      if (FirstCall) {
        var handler = (HttpClientHandler) this.InnerHandler;
        handler.Proxy = this.Proxy;
        handler.UseProxy = true;
        FirstCall = false;
      }
      return base.SendAsync(request, cancellationToken);
    }
  }
}

将其传递给客户端的构造函数。

var account = CloudStorageAccount.Parse (connectionString);  
var client = new CloudBlobClient (account.BlobEndpoint, account.Credentials, new ProxyInjectionHandler (new WebProxy (new Uri (proxyUrl))));  
var container = client.GetContainerReference ("...");  
await container.CreateIfNotExistsAsync ();

参考资料: