一、新建项目:WebHtpsDemo
二、生成pfx证书
拷贝到项目中
三、修改配置文件appsettings.Development.json
{
"KestrelSettings": {
"IP": "192.168.31.68",
"Port": 8189,
"CerPath": "xxxCert.pfx",
"CerPassword": "Ux938CF8@929",
"EnableHttps": false
}
}
四、修改:Program.cs
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace WebHtpsDemo
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseKestrel(configureOptions =>
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var config = new ConfigurationBuilder();
var configurationBuilder = config.SetBasePath(Directory.GetCurrentDirectory());
configurationBuilder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{environment}.json", optional: false, reloadOnChange: true);
var buildConfig = configurationBuilder.Build();
var ip = buildConfig.GetValue<string>("KestrelSettings:IP");
var port = buildConfig.GetValue<int>("KestrelSettings:Port");
var cerPath = buildConfig.GetValue<string>("KestrelSettings:CerPath");
var cerPassword = buildConfig.GetValue<string>("KestrelSettings:CerPassword");
var enableHttps = buildConfig.GetValue<bool>("KestrelSettings:EnableHttps");
if(enableHttps)
{
configureOptions.Listen(IPAddress.Parse(ip), port, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;//想支gRPC 必须Http2
listenOptions.UseHttps(cerPath, cerPassword);
});
}
else
{
webBuilder.UseUrls($"http://{ip}:{port}");
}
});
webBuilder.UseStartup<Startup>();
});
}
}
修改:Startup.cs
var enableHttps = Configuration.GetValue<bool>("KestrelSettings:EnableHttps");
if (enableHttps)
{
app.UseHsts();
app.UseHttpsRedirection();
}
五、运行效果:
Linux 启动:
export ASPNETCORE_ENVIRONMENT=Production
dotnet WebHtpsDemo.dll