.Net Core 发送https请求/.net core 调用数字证书 使用X509Certificate2

.Net Core 发送https请求

.net core 调用数字证书 使用X509Certificate2

 

.NET下面的 .netfromwork使用和asp.net core下使用方式不一样

 

.Net Core中的使用方式代码:

        /// 
        /// 指定Post地址使用Get 方式获取全部字符串
        /// 
        /// 请求后台地址
        /// Post提交数据内容(utf-8编码的)
        /// 
        public static string PostSsl3(string url, string content)
        {
            string path = @"D:\Site\QL.Back.API\wwwroot\file\cert\apiclient_cert.p12";
            string password = "xxxx";

            //HttpClient请求,在handler里添加X509Certificate2 证书,数据data是byte[] 类型,所以需要使用ByteArrayContent传入
            var handler = new HttpClientHandler();
            handler.ClientCertificateOptions = ClientCertificateOption.Manual;
            handler.SslProtocols = SslProtocols.Tls12;
            //获取证书路径
            //商户私钥证书,用于对请求报文进行签名
            handler.ClientCertificates.Add(new X509Certificate2(path, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet));
            handler.SslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
            handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
            //post请求
            var client = new HttpClient(handler);
            using (MemoryStream ms = new MemoryStream())
            {
                byte[] bytes = Encoding.UTF8.GetBytes(content);
                ms.Write(bytes, 0, bytes.Length);
                ms.Seek(0, SeekOrigin.Begin);//设置指针读取位置,否则发送无效
                HttpContent hc = new StreamContent(ms);
                var response = client.PostAsync(url, hc).Result;
                return response.Content.ReadAsStringAsync().Result;
            }
        }

 

更多:

.Net Standard HttpClient封装Htt请求常用操作整理

.Net Standard Http请求实例

.Net Standard 类库的创建和使用

转载于:https://www.cnblogs.com/tianma3798/p/11321981.html

你可能感兴趣的:(.Net Core 发送https请求/.net core 调用数字证书 使用X509Certificate2)