以前寫過的程序,都是普通http request。url
這是第一次使用,記錄下。spa
1 private static X509Certificate2 GetCert(string certId,StoreLocation location) 2 { 3 X509Certificate2 result = null; 4 X509Store certStore; 5 certStore = new X509Store(StoreName.My, location); 6 certStore.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadOnly); 7 8 try 9 { 10 X509Certificate2Collection set = certStore.Certificates.Find( 11 X509FindType.FindByThumbprint, certId, true); 12 13 if (set.Count > 0 && set[0] != null && set[0].HasPrivateKey) 14 { 15 result = set[0]; 16 } 17 } 18 finally 19 { 20 certStore.Close(); 21 } 22 23 return result; 24 }
說明:命令行
命名空間:code
using System.Security.Cryptography.X509Certificates;blog
certID:string
證書含有一個指紋(thumbprint),就是certId。在證書的detail中能夠查看,注意他們之間的空格,很容易copy錯誤;it
Location:io
兩個類別:class
CurrentUser,LocalMachine。命令行mmc而後找到證書管理。命名空間
調用:
req = WebRequest.CreateHttp(url);
// add in the cert we'll authenticate with
req.ClientCertificates.Add(GetCert(thumbprint,StoreLocation.CurrentUser));
這樣就建立了一個須要證書的請求。