.Net Core 發送https請求html
.net core 調用數字證書 使用X509Certificate2api
.NET下面的 .netfromwork使用和asp.net core下使用方式不同asp.net
.Net Core中的使用方式代碼:post
/// <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; } }
更多:編碼