How to add client certificate in ASP.NET Web API i

2019-02-26 08:42发布

问题:

I want to test my Web API service using in-memory HttpServer.

The current setup looks the following:

 var httpConfig = CreateTestHttpConfiguration();
 var server = new HttpServer(httpConfig);

 var handler = new WebRequestHandler();
 var cert = new X509Certificate2("filename", "password");
 handler.ClientCertificates.Add(cert);
 var client = HttpClientFactory.Create(handler, server);

I can make requests to the server using these client and everything works except that certificate is not added to the request.

As I understand that happens since server executes before handler (I can't rearrange them since they implement different interfaces) and since server immediately responses handler is not even executed (I've tested this assumption using HttpClientHandler subclass instead of handler).

So my question is: How can I add the client certificate for in-memory testing?

回答1:

This approach will do it:

        var server = new HttpServer(configuration);
        var invoker = new HttpMessageInvoker(server);
        var certificate = GetCertificate();

        var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/YourPath");
        request.Properties[HttpPropertyKeys.ClientCertificateKey] = certificate;
        var result = await invoker.SendAsync(request, CancellationToken.None);