要将HTTP请求改为HTTPS请求,这可不是简单的将HTTP改为HTTPS就可以了,你尝试下,就知道这是不行的。
而本文将介绍C#如何将调用WebService接口的HTTP请求改为HTTPS请求。
若是是其他语言,请关闭此页。
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="xxx">
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="Certificate" algorithmSuite="Default" />
security>
binding>
basicHttpBinding>
bindings>
<client>
<endpoint address="https://xxx" binding="basicHttpBinding" />
client>
system.serviceModel>
configuration>
可以使用浏览器查看接口使用了哪个TLS版本:
使用Chrome浏览器
1.把接口地址拷贝到Chrome浏览器打开
2.右键单击当前页面,然后选择“检查”;
3.然后单击“Security”选项以查看此页面上使用的TLS版本。
4.如果我们看不到当前页面的TLS版本,我们可以 单击左侧的“Main origin”,然后在右侧,你可以看到“Connection”属性下的“Protocol”显示了TLS版本。
为了支持TLS,因此还需要要设置安全协议的版本。
由于.NET 4.0最多支持TLS 1.0,而.NET 4.5最多支持TLS 1.2。
因此根据应用程序使用.NET版本分两种情况来设置。(代码请添加在程序入口或调用接口前)
ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
为什么是192、768、3072,因为在.NET4.5就是这样的TLS版本对应关系:
namespace System.Net
{
[System.Flags]
public enum SecurityProtocolType
{
Ssl3 = 48,
Tls = 192,
Tls11 = 768,
Tls12 = 3072,
}
}
ServicePointManager.SecurityProtocol =
SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
.NET 4.0使用以上代码会报错,因为找不到Tlsl11
和Tls12
当然你也可以根据TLS的版本来设置SecurityProtocol。
上一步已经说了:由于.NET 4.0最多支持TLS 1.0,而.NET 4.5最多支持TLS 1.2。
因此TLS版本大于1.0程序所在的电脑需安装.NET 4.5。
安装后提示需要重启电脑,实际上不用重启HTTPS请求就能够成功调用。