How to add client certificate in ASP.NET Web API in-memory testing?

假装没事ソ 提交于 2020-01-11 10:41:52

问题


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);


来源:https://stackoverflow.com/questions/28285055/how-to-add-client-certificate-in-asp-net-web-api-in-memory-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!