c# - 为 c# Post 使用不受信任的 ssl 证书

标签 c# iis ssl https posting

我们已经在 IIS6 中创建了一个证书,并将其应用到一个使用 SSL 的站点。 现在,我们之前使用的相同程序将无法运行。据我了解,c# 透明地支持 HTTPS,因此我相信它必须使用“不受信任”的证书。关闭代理设置后(出现 403 禁止错误),我收到“无法为 SSL 建立信任关系”

我已经尝试了一些变通办法,比如用验证 hack 交换默认证书策略,但它已经很老了,我仍然遇到同样的错误。

下面是我的发帖方法。

 try
    {
        HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
        HttpWebRequest.DefaultCachePolicy = policy;


        byte[] buffer = Encoding.UTF8.GetBytes(postData);
        //Initialisation
        HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(url);
        WebReq.Timeout = 10000;
        //method is post

        if (useproxy == "ON")
        {
            WebProxy myProxy = new WebProxy();
            // Create a new Uri object.
            Uri newUri = new Uri(proxy);

            // Associate the new Uri object to the myProxy object.
            myProxy.Address = newUri;
            WebReq.Proxy = myProxy;
        }


        WebReq.KeepAlive = false;
        WebReq.Method = "POST";
        WebReq.ContentType = "application/x-www-form-urlencoded";


        //The length of the buffer 
        WebReq.ContentLength = buffer.Length;
        Stream PostData = WebReq.GetRequestStream();
        //write, and close. 
        PostData.Write(buffer, 0, buffer.Length);
        PostData.Close();

        //Get the response handle
        HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();

        Console.WriteLine(WebResp.StatusCode);
        Console.WriteLine(WebResp.Server);

        //Do not worry about response!. 
        //read the response (the string), and output it.
        Stream Answer = WebResp.GetResponseStream();
        StreamReader _Answer = new StreamReader(Answer);
        vystup = _Answer.ReadToEnd();


        if (vystup != "OK")
        {

        }
    }
    catch (WebException ex)
    {

        Console.WriteLine(ex);
    }

证书或我的应用程序或 IIS 中是否有解决此问题的解决方法?大概是它的 C# 不信任证书,但这是我第一次使用 Https。

欢迎提供任何信息。

最佳答案

默认情况下,.NET 证书策略将拒绝任何未经验证或不受信任的服务器证书,因为 99% 的情况下这就是您想要的。 (默认情况下唯一通过的“坏”证书已过期,但其他有效证书。)

您有几种选择,具体取决于您所谈论的部署规模。

  1. 将服务器的证书作为受信任的根证书安装在客户端上。对于测试,这是最简单的选择,我一直使用我的开发机器的 IIS 和 IIS Express 证书进行测试。不过,可怕的生产想法。

  2. 使用内部 CA 生成证书;如果您在一家拥有 Active Directory 设置的公司工作,则 AD 服务器可以充当 CA,并且您可以使用组策略将 AD 服务器的 CA 根目录自动推送到客户端。如果您要在内部部署某些东西,这是一个不错的方法,因为它非常便宜:)

  3. 实现 ServerCertificateValidationCallback在忽略任何 SSL 错误的 ServicePointManager 类上。这里唯一真正的陷阱是这是一个全局设置,因此 每次 使用 WebRequest 类都将使用您的自定义验证回调。

关于c# - 为 c# Post 使用不受信任的 ssl 证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10849959/

相关文章:

c# - 是否可以在 IIS HttpModule 中修改 HttpRequest POST 的内容?

c# - 为什么 C# 队列或列表只有计数而数组有长度?

c# - 添加事件处理程序

tomcat - 为什么 IIS 给我一个 tomcat 错误

c# - 如何在数据库中保存图像 URL?

c# - 反转数学函数

tomcat - 在 GoDaddy 的 VPS Windows server 2008 R2 上使 Tomcat 默认网络服务器

linux - Icecast 2 和 SSL

git - 无法克隆 repo 。服务器证书验证失败

ssl - 与公共(public)服务器的 OPENSSL 连接给出 X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY