c# – Request.HttpContext.Connection.ClientCertificate始终为null

我有一个ASP.Net核心网站部署在
Linux的Azure应用服务上.

在控制器中,我试图获得如下的客户端证书:

var callerCertificate = Request.HttpContext.Connection.ClientCertificate;

我总是将callerCertificate作为null.
我试过等待Request.HttpContext.Connection.GetClientCertificateAsync(),结果为null.

我的网站webhost创建如下所示:

WebHost.CreateDefaultBuilder(args)
                .UseKestrel()
                .UseStartup<Startup>()
                .UseSerilog();

我还为网站设置了SSL设置(在Azure中),如下所示:

《c# – Request.HttpContext.Connection.ClientCertificate始终为null》

客户端调用者是net462项目,它使用Microsoft.Rest.CertificateCredentials将证书设置为HTTP请求.

var cred = new CertificateCredentials(_deviceCertificate)
...
await this.cred.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);

最佳答案 您可以尝试直接使用HttpClient添加证书,而不是使用Microsoft.Rest.CertificateCredential.

var clientHandler = new HttpClientHandler();
clientHandler.ClientCertificateOptions = ClientCertificateOption.Manual;
clientHandler.ClientCertificates.Add(_deviceCertificate);

var client = new HttpClient(clientHandler);
var result = client.GetAsync("https://yourservice").GetAwaiter().GetResult();

您可能还需要配置SSL协议(SSL2,SSL3,TLS等):

clientHandler.SslProtocols = SslProtocols.Tls;
点赞