C#调用webapi HTTPS报错:基础连接已经关闭: 未能为 SSL/TLS 安全通道建立信任关系--安全证书问题

5 篇文章 0 订阅
3 篇文章 0 订阅

1、首先加入命名空间:
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

SSL网站,连接时需要提供证书,对于非必须提供客户端证书的情况,只要返回一个安全确认即可。我的是.NET FrameWork4.0

2、加入以下代码:

 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
    {
        //直接确认,否则打不开
        return true;
    }

3、接收证书进行身份验证ssl,在调用api接口前调用此方法:
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);

以下是完整案例:

 public string HttpPost(string url, string body)
    {
        Encoding encoding = Encoding.UTF8;
        string jsonText = string.Empty;
        string dataText1 = string.Empty;
        if (string.IsNullOrEmpty(url.Trim()))
        {
            return "";
        }
        //接收证书进行身份验证
        ServicePointManager.ServerCertificateValidationCallback =
            new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);
        //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "POST";
        request.Accept = "text/plain, */*; q=0.01";
        request.ContentType = "application/json;charset=utf-8";
        byte[] buffer = encoding.GetBytes(body);
        request.ContentLength = buffer.Length;
        request.GetRequestStream().Write(buffer, 0, buffer.Length);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
        {
            jsonText = reader.ReadToEnd();
            dataText1 = Regex.Replace(jsonText, @"\\", "");
        }
        return dataText1;
    }

调用:
dlbzUrl是调用地址 https://…/api/tddbzzljcxt/zybrxx/vnoentry-query
model.FCYRQSTART 开始时间
model.FCYRQEND 结束时间

  string DaliBaiHospitalJson = HttpPost(dlbzUrl, "{\"FIDATES\":\"" + model.FCYRQSTART + " 00:00:00" + "\",\"FIDATEE\":\"" + model.FCYRQEND + " 23:59:59" + "\"}");
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值