如何在 Universal Windows App 中使用 System.Net.Http.HttpClient 忽略自签名证书

How to ignor self signed certificates with System.Net.Http.HttpClient in Universal Windows App

我正在创建一个便携式 Class 库,这意味着据我所知,我必须使用 System.Net.Http.HttpClient 来调用我的网络 API。挑战在于,对于我的通用 Windows 应用程序,由于 API 服务器可以拥有自签名证书这一事实,我无法弄清楚如何忽略返回的错误。任何建议将不胜感激。

更新:我无法导入任何证书,因为这将是一个在各种组织的各种设备上运行的应用程序,并且让他们将自签名证书导入每个设备 运行 应用程序是不切实际的。

不是一个选项,因为 System.Net.ServicePointManager.CertificatePolicy 在 UWP 中不可用。如果您改用 Windows.Web.Http.HttpClient,则可以 ignore self signed certificates.

更新:

再想一想,如果将自签名证书添加到应用程序的根证书中,则可以忽略自签名证书错误。

两个选项:

  • 使用 API 安装它:

    IBuffer buffer = await FileIO.ReadBufferAsync(file);
    Certificate rootCert = new Certificate(buffer); 
    CertificateStore rootStore = CertificateStores.TrustedRootCertificationAuthorities;
    rootStore.Add(rootCert);
    
  • 将其包含在您的 Package.appxmanifest > 声明 > 证书 > 添加 并设置:

    • 店名:root
    • 内容:证书文件路径

使用这两个选项中的任何一个,您将停止获得:

System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.