.net core 配置安全证书及访问Https接口
- 加载安全证书访问Https接口,代码如下
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
static HttpWebRequest getRequest() { HttpWebRequest request = null; if (request == null) { if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { request = WebRequest.Create(url) as HttpWebRequest; //添加证书 X509Certificate2 x509Certificate2 = new X509Certificate2(Directory.GetCurrentDirectory() + @"\StaticFile\my.p12", "IoM@1234", X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); request.ClientCertificates.Add(x509Certificate2); ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request.ProtocolVersion = HttpVersion.Version11; // 这里设置了协议类型。 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;// (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = 1000; ServicePointManager.Expect100Continue = false; } else { request = (HttpWebRequest)WebRequest.Create(url); } request.Method = "POST"; //使用get方式发送数据 request.KeepAlive = true; request.Proxy = null; request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8"; request.Referer = null; request.AllowAutoRedirect = true; //request.ServicePoint.Expect100Continue = false; //request.ServicePoint.UseNagleAlgorithm = false; request.AllowWriteStreamBuffering = false; request.Timeout = 1000 * 10; request.ReadWriteTimeout = 1000 * 10; //request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; request.Accept = "*/*"; } return request; }
- .net core 配置Https并引入安全文件,代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseKestrel(options => { options.Listen(IPAddress.Loopback, 5001, listenOptions => { listenOptions.UseHttps(AppContext.BaseDirectory+@"\my.p12", "IoM@1234"); }); }) .UseIIS(); }