我已经建立了一个简单的 Web API 项目,它强制执行 https,
当我从浏览器调用服务时,我得到了正确的结果:
But how do I call this service from a WPF client?
调用“非”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/");
...
How do I call my https://... service?
最佳答案
我知道你已经解决了你的问题。但是我回答只是为了更新您和其他新用户的信息,他们应该使用 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)};
然后你就可以做任何你想做的事了。
希望有帮助。
关于c#-4.0 - 通过 SSL 从 WPF 进行 Web api 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23455658/