为ASP.NetCore程序启用SSL
紧接着上一篇搭建连接MySql的三层架构的ASP.NetCore2.0的WebApi的案例,这篇来实现为ASP.NetCore启用SSL支持
由于ASP.NetCore默认服务器Kestrel不像iis Express那样会自动生成本地证书,所以就需要手动构建pfx证书.
生成pfx证书
开发环境证书就用iis默认的本地证书即可,Cortana搜索:IIS,出现以下结果点击
进入管理器:点击服务器证书选项
选中以下本地默认证书后右键导出,指定路径和密码点击确认.
修改Program中BuildWebHost以增加SSL支持
第一种方案:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System.Net; namespace ASP.Net_Core_API { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseKestrel(options =>//设置Kestrel服务器 { options.Listen(IPAddress.Loopback, 5001, listenOptions => {
//填入之前iis中生成的pfx文件路径和指定的密码
listenOptions.UseHttps("D:\\DotNetCore\\ASP.Net Core API\\wwwroot\\dontCore.pfx", "111111");
});
})
.Build();
}
}
此种方案无需更改其他代码即可生效,点击运行
可看到已监听指定的端口5001,浏览器输入https://127.0.0.1:5001/api/values,可看到已启用ssl
第二种方案:同时支持http和https请求(基于appsettings.json配置)
由于上一种方案只支持https请求,但实际生产也需要http请求
实现核心代码:
Program:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System.Net; namespace ASP.Net_Core_API { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseKestrel(SetHost)//启用Kestrel .Build(); /// <summary> /// 配置Kestrel /// </summary> /// <param name="options"></param> private static void SetHost(Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions options) { var configuration = (IConfiguration)options.ApplicationServices.GetService(typeof(IConfiguration)); var host = configuration.GetSection("RafHost").Get<Host>();//依据Host类反序列化appsettings.json中指定节点 foreach (var endpointKvp in host.Endpoints) { var endpointName = endpointKvp.Key; var endpoint = endpointKvp.Value;//获取appsettings.json的相关配置信息 if (!endpoint.IsEnabled) { continue; } var address = IPAddress.Parse(endpoint.Address); options.Listen(address, endpoint.Port, opt => { if (endpoint.Certificate != null)//证书不为空使用UserHttps { switch (endpoint.Certificate.Source) { case "File": opt.UseHttps(endpoint.Certificate.Path, endpoint.Certificate.Password); break; default: throw new NotImplementedException($"文件 {endpoint.Certificate.Source}还没有实现"); } //opt.UseConnectionLogging(); } }); options.UseSystemd(); } } } /// <summary> /// 待反序列化节点 /// </summary> public class Host { /// <summary> /// appsettings.json字典 /// </summary> public Dictionary<string, Endpoint> Endpoints { get; set; } } /// <summary> /// 终结点 /// </summary> public class Endpoint { /// <summary> /// 是否启用 /// </summary> public bool IsEnabled { get; set; } /// <summary> /// ip地址 /// </summary> public string Address { get; set; } /// <summary> /// 端口号 /// </summary> public int Port { get; set; } /// <summary> /// 证书 /// </summary> public Certificate Certificate { get; set; } } /// <summary> /// 证书类 /// </summary> public class Certificate { /// <summary> /// 源 /// </summary> public string Source { get; set; } /// <summary> /// 证书路径() /// </summary> public string Path { get; set; } /// <summary> /// 证书密钥 /// </summary> public string Password { get; set; } } }
appsettings.json
{ "ConnectionStrings": { "MySqlConnection": "Server=localhost;database=NetCore_WebAPI-Mysql;uid=root;pwd=111111;" }, "Logging": { "IncludeScopes": false, "Debug": { "LogLevel": { "Default": "Warning" } }, "Console": { "LogLevel": { "Default": "Warning" } } },
//以下为Kestrel配置信息,同时支持https和HTTP "RafHost": { "Endpoints": { "Http": { "IsEnabled": true, "Address": "127.0.0.1", "Port": "5000" }, "Https": { "IsEnabled": true, "Address": "127.0.0.1", "Port": "5443", "Certificate": { "Source": "File", "Path": "wwwroot\\dontCore.pfx", "Password": "111111" } } } } }
点击运行会发现控制台出现监听两个端口的提示,一个支持https一个支持http
浏览器输入http://127.0.0.1:5000/api/values
http请求运行正常
再输入https://127.0.0.1:5443/api/values
https运行正常
专案下载链接:Demo
作者:Chaunce
GitHub:https://github.com/liuyl1992
公众号请搜:架构师高级俱乐部 SmartLife_com
声明:原创博客请在转载时保留原文链接或者在文章开头加上本人博客地址,如发现错误,欢迎批评指正。凡是转载于本人的文章,不能设置打赏功能等盈利行为