天天看點

.Net Core 發送https請求/.net core 調用數字證書 使用X509Certificate2

.Net Core 發送https請求

.net core 調用數字證書 使用X509Certificate2

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

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

/// <summary>
        /// 指定Post位址使用Get 方式擷取全部字元串
        /// </summary>
        /// <param name="url">請求背景位址</param>
        /// <param name="content">Post送出資料内容(utf-8編碼的)</param>
        /// <returns></returns>
        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;
            }
        }