1. 将证书安装到服务器上
开始 -> 运行 ->输入 mmc 进入控制台界面
2. 选择 “证书” ->“计算机账户”->“下一步”->“完成”
3. 选择相关的证书进行导入
3. 把证书颁发给IIS程序使用,需要使用的工具 Windows HTTP Services Certificate Configuration Tool
工具默认安装的目录为: 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;
}