ASP.NET Core 2.1:将客户端证书添加到已注册的键入HTTP客户端

时间:2018-08-14 21:30:47

标签: c# asp.net asp.net-core dotnet-httpclient

我介绍了ASP.NET Core 2.1的新方法,用于在我的应用程序中创建/注册HTTP客户端,如所述here。在我需要将客户端证书添加到键入的HTTP客户端之前,它一直工作良好。

我做了很多研究,但没有找到一种方法。

我希望这样:

services.AddHttpClient<IMonitoringService, MonitoringService>(
            client =>
            {
                client.BaseAddress = new Uri(this.Configuration.GetSection("ServiceEndpoints:Monitoring").Get<ServiceEndpointConfiguration>().Endpoint);
                client.ClientCertificates.Add(new X509Certificate2(/* ... */)); // Error: `ClientCertificates` doesn't exists.
            });

或者那样:

services.AddHttpClient<IMonitoringService, MonitoringService>(
                client => client.BaseAddress = new Uri(this.Configuration.GetSection("ServiceEndpoints:Monitoring").Get<ServiceEndpointConfiguration>().Endpoint))
            .AddHttpMessageHandler(
                () =>
                {
                    var handler = new HttpClientHandler();
                    handler.ClientCertificates.Add(new X509Certificate2(/* ... */));
                    return handler; // Error: Expected return type is `DelegatingHandler`.
                });

但是这种方式不存在。

有办法吗?

1 个答案:

答案 0 :(得分:1)

您的经验是正确的,因为此函数用于扩展请求管道,所以需要// Gets fired on button click onSendEmailClick(): void { if (this.selectedEmail.Content) { let attachments = this.assignEmailContent(); this.fireAfterCompleted(attachments); } } // Gets called by button click assignEmailContent() { return this.assignEmailAttachments(); } // Need attachmentsArray to be fully populated before returning items async assignEmailAttachments() { let attachmentArray: any[] = this.selectedAttachments.map(async (item) => { const response = await this.subscribeToContainerItem(item); attachmentArray.push(response); }); return attachmentArray; } // Calls a API method to get item async subscribeToContainerItem(item: any) { this._azureStorageService.getContainerItemByContainerIdItemName(this._routeIdService.getStorageContainerId(), item.Name).subscribe(async (res: any) => { return ({ filename: item.Name, path: res.url }); }, err => { return (err); }); } // API Request getContainerItemByContainerIdItemName(containerId: string, itemName: string) { let httpOptions = this.prepareOptions(); return this._http.get(environment.API + containerId + '/' + itemName, httpOptions); } 返回类型AddHttpMessageHandler。为了创建带有客户端证书的DelegatingHandler,您应该使用HttpClientHandler创建并返回ConfigurePrimaryHttpMessageHandler的配置实例。