.NET Core Kestrel部署HTTPS以及Docker部署HTTPS

一:右键项目管理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/

由于证书是自己生成,显示不安全也就是没有得到验证。

原文地址:https://www.cnblogs.com/ZhengHengWU/p/12836665.html