【问题标题】:web api call from WPF over SSL通过 SSL 从 WPF 调用 web api
【发布时间】:2014-05-04 11:23:30
【问题描述】:
我已经建立了一个简单的 Web API 项目,它强制执行 https,
当我从浏览器调用服务时,我得到了正确的结果:
但是如何从 WPF 客户端调用此服务?
调用“非”https 服务不会给我带来任何问题:
HttpClient client = new HttpClient()
{
BaseAddress = new Uri("http://localhost:49838/")
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
HttpResponseMessage response = await client.GetAsync("/api/products/");
...
如何调用我的 https://... 服务?
【问题讨论】:
标签:
c#-4.0
ssl
https
asp.net-web-api
asp.net-web-api2
【解决方案1】:
我知道你已经解决了你的问题。 Bur 我回答只是为了更新您和其他新用户,他们应该使用 HttpClient 类而不是 WebRequest。
阅读有关 HTTPClient 的更多信息 - HttpClient is Here!
HttpClient 是更强大和改进的工具。 HttpClient 是 .NET 的现代 HTTP 客户端。它提供了一个灵活且可扩展的 API,用于访问通过 HTTP 公开的所有内容。
这里是检查来自受信任的根证书颁发机构 (StoreName.Root) 的证书的示例方法,它将检查本地计算机 (StoreLocation.LocalMachine) 中的证书。
X509Certificate2 cert = null;
X509Store store = null;
try
{
store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly);
// You can check certificate here ...
// and populate cert variable..
}
finally
{
if (store != null) store.Close();
}
var clientHandler = new WebRequestHandler();
if (cert != null) clientHandler.ClientCertificates.Add(cert);
var client = new HttpClient(clientHandler) {BaseAddress = new Uri(uri)};
然后你就可以为所欲为。
希望对您有所帮助。