一:右鍵項目管理NUGet包添加引用 Microsoft.AspNetCore.Server.Kestrel.Https。
二:生成證書
生成證書見:https://www.cnblogs.com/ZhengHengWU/p/12836426.html
最終得到的server.pfx 就是可以用來在配置HTTPS。
三:啟用SSL
(1) 在Configure方法中啟用https
app.UseHttpsRedirection();
(2) 新建 httpsConfig.json 配置
{ "pfx_name": "server.pfx", "pfx_pswd": "wuzhd", "server_port": 443 }
(3) 在Program類中配置Kestrel
public static IWebHostBuilder CreateWebHostBuilder(string[] args) { var dic = ReadConfig(); return WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .ConfigureKestrel(options => { options.Listen(IPAddress.Any, Convert.ToInt32(dic["server_port"]), listenOptions => { listenOptions.UseHttps(dic["pfx_name"], dic["pfx_pswd"]); }); }) .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration(); }
private static Dictionary<string, string> ReadConfig() { try { using (FileStream fs = new FileStream("httpsConfig.json", FileMode.Open)) { using (StreamReader sr = new StreamReader(fs)) { return JsonConvert.DeserializeObject<Dictionary<string, string>>(sr.ReadToEnd()); } } } catch (Exception ex) { throw ex; } }
四:Docker中生成ssl證書
更新Dockerfile文件
FROM microsoft/dotnet:2.2-aspnetcore-runtime FROM mcr.microsoft.com/dotnet/core/sdk:2.2 WORKDIR /app COPY . /app WORKDIR /app ENV ASPNETCORE_URLS http://+:443 ENV ASPNETCORE_ENVIRONMENT=Production EXPOSE 443 ENV certPassword wuzhd RUN openssl genrsa -des3 -passout pass:${certPassword} -out server.key 2048 RUN openssl rsa -passin pass:${certPassword} -in server.key -out server.key RUN openssl req -sha256 -new -key server.key -out server.csr -subj '/CN=wuzhd' RUN openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt RUN openssl pkcs12 -export -out server.pfx -inkey server.key -in server.crt -certfile server.crt -passout pass:${certPassword} CMD ["dotnet", "Api.dll"]
然后選擇使用 Kestrel 運行。
打開瀏覽器輸入 https://localhost/
由於證書是自己生成,顯示不安全也就是沒有得到驗證。