2017-05-05 205 views
1

我們正在使用AutoRest基於API Swagger文件生成客戶端代碼。如何使用AutoRest客戶端傳遞客戶端證書

我試圖將客戶端證書傳遞給API。但注意到生成的客戶端代碼不接受WebRequestHandler。

生成的代碼看起來像下面:

public MyTestApiV1(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) 
     { 
      if (baseUri == null) 
      { 
       throw new ArgumentNullException("baseUri"); 
      } 
      this.BaseUri = baseUri; 
     } 

我覺得我失去了一些東西。有沒有人設法使用AutoRest發送客戶端證書?

試過,但webRequestHandler始終爲空:

var webRequestHandler = client.HttpMessageHandlers.First() as WebRequestHandler; 
      if (webRequestHandler != null) 
      { 
       var secretRetrieved = keyVault.GetSecretAsync("my-cert"); 
       var pfxBytes = Convert.FromBase64String(secretRetrieved.Result); 
       // or recreate the certificate directly 
       var certificate = new X509Certificate2(pfxBytes); 
       webRequestHandler.ClientCertificates.Add(certificate); 
      } 
+0

您可能需要使用[揚鞭代碼生成(https://github.com/swagger-api/swagger-codegen)生成C#API客戶端代替,並按照HTTP嘗試: //stackoverflow.com/questions/34506086/how-to-restsharp-add-client-certificate-in-https-request-c添加客戶端證書。 –

+0

是的,這是由autorest codegen –

+0

生成的代碼。我不熟悉Autorest生成的C#代碼。我的建議是嘗試一種不同的生成器,它可以在C#API客戶端中附加客戶端證書。 –

回答

1

您可以使用另一個重載的構造函數:

/// <summary> 
/// Initializes ServiceClient using base HttpClientHandler and list of handlers. 
/// </summary> 
/// <param name="rootHandler">Base HttpClientHandler.</param> 
/// <param name="handlers">List of handlers from top to bottom (outer handler is the first in the list)</param> 
protected ServiceClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) 

ServiceClient是產生客戶的基類。因此,代碼可能看起來像:

var secretRetrieved = keyVault.GetSecretAsync("my-cert"); 
var pfxBytes = Convert.FromBase64String(secretRetrieved.Result); 
// or recreate the certificate directly 
var certificate = new X509Certificate2(pfxBytes); 
WebRequestHandler webRequestHandler = new WebRequestHandler(); 
webRequestHandler.ClientCertificates.Add(certificate); 
var client = new MyTestApiV1(webRequestHandler); 
client.BaseUri = baseUri;