c#-4.0 - 通过 SSL 从 WPF 进行 Web api 调用

标签 c#-4.0 ssl https asp.net-web-api asp.net-web-api2

我已经建立了一个简单的 Web API 项目,它强制执行 https,

IIS express configuration

当我从浏览器调用服务时,我得到了正确的结果:

enter image description here

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/

相关文章:

Linq OrderBy 但如果 "the"忽略第一个单词

linux - 获取 -enddate 时 Openssl 输出挂起

ssl - 将自签名证书添加到 ubuntu 以与 curl 一起使用

ssl - Nginx中的负载平衡-TCP,SSL,HTTPS

asp.net - 导出Excel前添加标题

c# - 如何使类真正不可变?

c# - HttpContext.Current.User.Identity.IsAuthenticated 在登录控件 LoggedIn 事件中为 false

ssl - NGINX - 此处不允许使用 "server"指令

apache - FQDN 上的 SSL 与 IP

node.js - HTTPS 使用 Node Js 渲染 html 文件