1. 程式人生 > >C# HttpClient 帶證書的https 請求

C# HttpClient 帶證書的https 請求

1. 將證書安裝到伺服器上

開始 -> 執行 ->輸入 mmc 進入控制檯介面

2.  選擇 “證書” ->“計算機賬戶”->“下一步”->“完成”

3. 選擇相關的證書進行匯入


工具預設安裝的目錄為: C:\Program Files (x86)\Windows Resource Kits\Tools

開啟cmd,鍵入: winhttpcertcfg -g -c LOCAL_MACHINE\WebSite -s "你的證書名稱" -a "你的iis賬號標識"

-g 授權,-c 證書所在的儲存區

證書的名稱就是上圖顯示的 "CTS-IT-203"

IIS賬號標識


4. C#程式程式碼

        internal static string PostHttpsAsync(string url,Dictionary<string,string> parameters,string certName)
        {
            WebRequestHandler handler = new WebRequestHandler();
            X509Certificate2 certificate = GetMyX509Certificate(certName);
            handler.ClientCertificates.Add(certificate);
            using (var client = new HttpClient(handler))
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(parameters));
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                var response = client.PostAsync(url, httpContent);
                var body = response.Result.Content.ReadAsStringAsync().Result;
                return body;
            }
        }
        internal static X509Certificate2 GetMyX509Certificate(string certName)
        {
            X509Store store = new X509Store("Wetrial", StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);            
            X509Certificate2 cert = store.Certificates.Find(X509FindType.FindBySubjectName, certName, false)[0];
            return cert;
        }