在ASP.NET Core中,如果在Kestrel中想使用HTTPS對站點進行加密傳輸,可以按照如下方式
申請證書
這一步就不詳細說了,有免費的和收費的,申請完成之後會給你一個*.pfx結尾的文件。
添加NuGet包
nuget中查找然後再程序中添加引用Microsoft.AspNetCore.Server.Kestrel.Https
配置
把*.pfx結尾的文件拷貝的程序的Web根目錄,然後修改Programs.cs文件:
public class Program
{
public static void Main(string[] args) {
var config = new ConfigurationBuilder().AddCommandLine(args).AddEnvironmentVariables("ASPNETCORE_").Build();
var host =
new WebHostBuilder().UseConfiguration(config).UseKestrel(ConfigHttps()).UseContentRoot(
Directory.GetCurrentDirectory()).UseIISIntegration().UseStartup<Startup>().Build();
host.Run();
}
private static Action<KestrelServerOptions> ConfigHttps() {
return x => {
var pfxFile = Path.Combine(Directory.GetCurrentDirectory(), "*.pfx");
//password 填寫申請的密鑰
var certificate = new X509Certificate2(pfxFile, "password");
x.UseHttps(certificate);
};
}
}
然後命令行窗口運行dotnet xxx.dll --server.urls https://www.example.com:port即可。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。