C#访问HttpWebRequest和WebService(with SSL)

本文介绍了在C#中使用HttpWebRequest和WebService访问HTTPS服务时如何处理SSL证书,包括设置回调函数忽略证书验证错误,从本地加载证书到请求中。提供了测试通过的代码示例,涵盖HttpWebRequest直接调用、WebService引用以及通过wsdl.exe生成的客户端代理类三种方式。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

使用HttpWebRequest请求远端服务器时如何加载SSL证书。webservice的ssl方法太复杂,没验证。
http://www.cnblogs.com/fooo/archive/2008/10/31/1323396.html

C#访问WebService(with SSL)
http://xwhoyeah.javaeye.com/blog/101298

使用 HttpWebRequest 向网站提交数据
http://www.cnblogs.com/webman/archive/2006/11/17/564106.html
内部错误:未能为 SSL/TLS 安全通道建立信任关系。错误页面:根据验证过程,远程证书无效。经过分析,在浏览器中打开要进行一个安全确认。就是这个对话框引起的问题
http://www.zzchn.com/edu/20080727/92196.shtml

证书标准

http://www.shengfang.org/blog/p/200803100PKCScer.php

 

 

私钥安全性:

标准可交换cer证书文件是不包含私钥的,私人信息文件pfx里面才会包含有私钥。

 

包含证书和私钥的pfx文件导出:

选择的网站的目录安全性->查看证书->详细信息->导出pfx文件。

 

 

测试通过的代码,包括3种方式:HttpWebRequest和2个WebService(reference, wsdl.exe)

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Configuration;
using System.IO;
using System.Net.Security;

namespace Console
{
    class Program
    {
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        { // Always accept
            return true;
        }

        static void Main(string[] args)
        {
            ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);

            SSLWebRequestTest();
        }

        static void SSLWebRequestTest()
        {
            string reqUrl = "https://localhost/data/ReportSystemStatus.ashx";

            /// 构建请求的HttpWebRequest对象
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(reqUrl);
            req.KeepAlive = true;

            /// 从本地文件中加载证书
            req.ClientCertificates.Add(X509Certificate.CreateFromCertFile(ConfigurationManager.AppSettings["CertFilePath"]));
           
            string requestValue = "<request><ver>版本0.1</ver></request>";
            byte[] requestData = Encoding.UTF8.GetBytes(requestValue);

            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=UTF8";
            req.ContentLength = requestData.Length;

            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(requestData, 0, requestData.Length);
            }
            using (WebResponse wr = req.GetResponse())
            {
                //在这里对接收到的页面内容进行处理
                StreamReader reader = new StreamReader(wr.GetResponseStream(), Encoding.UTF8);
                string result = reader.ReadToEnd();
            }
        }

        static void SSLWebServiceReferenceTest()
        {
            ManageServices.ManangeServices ms = new ManageServices.ManangeServices();
            ms.ClientCertificates.Add(X509Certificate.CreateFromCertFile(ConfigurationManager.AppSettings["CertFilePath"]));

            string result = ms.CreateUser();
        }

        static void SSLWebServiceTest()
        {
            ManangeServices ms = new ManangeServices();
            ms.ClientCertificates.Add(X509Certificate.CreateFromCertFile(ConfigurationManager.AppSettings["CertFilePath"]));

            string result = ms.CreateUser();
        }
    }
}

 

app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
      <section name="Console.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    </sectionGroup>
  </configSections>
  <appSettings>
    <add key="CertFilePath" value="D:/svncode/Taishan/src/examples/APIServicesUsage/APIServices.cer" />
  </appSettings>
  <applicationSettings>
    <Console.Properties.Settings>
      <setting name="Console_ManageServices_ManangeServices" serializeAs="String">
        <value>https://localhost/ManangeServices.asmx</value>
      </setting>
    </Console.Properties.Settings>
  </applicationSettings>
</configuration>

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值