如何将客户端证书附加到AspNetCore TestServer api?

fle*_*sod 7 .net-core asp.net-core asp.net-core-2.0

我正在查看Microsoft.AspNetCore.TestHost.TestServerMicrosoft源代码.在那里,我看到CreateClient()属性是HttpClient对象.

那么如何在xUnit Test中附加Digitial Signature的客户端证书?

HttpClient 例子就是这样.

var x509Certificate2 = new X509Certificate();  // Pretend it contains certificate data already.

var httpClientHandler = new HttpClientHandler() {
    ClientCertificateOptions = ClientCertificateOption.Manual
};
httpClientHandler.ClientCertificates.Add(x509Certificate2);

using (var httpClient = new HttpClient(httpClientHandler))
{
}
Run Code Online (Sandbox Code Playgroud)

现在使用了 TestServer

var testServer = new TestServer();

testServer.CreateClient();  // How do I attached client certificate here?
Run Code Online (Sandbox Code Playgroud)

那么,我们如何在这里附上客户证书呢?对于CreateClient()

此外,我可以尝试实现HttpRequestMessage它,但它也不支持该证书选项.

小智 0

您可以尝试使用 testServer.SendAsync(...) 方法并从那里构造您的 HttpContext 。

var result = await server.SendAsync(context =>
                                    {
                                        context.Connection.ClientCertificate = myClientCertificate;
                                        context.Request.Method = "POST";
                                     });
Run Code Online (Sandbox Code Playgroud)

只需确保根据需要指定路径和正文即可。