使用证书创建request请求
之前写过的程序,都是普通http request。
这是第一次使用,记录下。
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 }
说明:
命名空间:
using System.Security.Cryptography.X509Certificates;
certID:
证书含有一个指纹(thumbprint),就是certId。在证书的detail中可以查看,注意他们之间的空格,很容易copy错误;
Location:
两个类别:
CurrentUser,LocalMachine。命令行mmc然后找到证书管理。
调用:
req = WebRequest.CreateHttp(url);
// add in the cert we'll authenticate with
req.ClientCertificates.Add(GetCert(thumbprint,StoreLocation.CurrentUser));
这样就创建了一个需要证书的请求。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 单线程的Redis速度为什么快?
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库