ASP.NET Core 3.1Web API:是否可以使用https作为Windows服务自托管,并使用像IIS这样的证书? [英] ASP.NET Core 3.1 Web API : can it be self-hosted as Windows service with https and use some certificate like IIS?

查看:27
本文介绍了ASP.NET Core 3.1Web API:是否可以使用https作为Windows服务自托管,并使用像IIS这样的证书?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是默认的ASP.NET Core 3.1 Web API应用程序,其中我已将其配置为https,也在使用app.UseHttpsRedirection();

现在我使用此Nuget包将其作为Windows服务托管:Microsoft.Extensions.Hosting.WindowsServices

托管已完成,但我正在使用http获取API结果,但在尝试使用httpsLIKEhttps://localhost:5001/weatherforecast

时出错

我是否可以创建一些类似IIS的自签名证书并分配它,并且可以作为https运行?

推荐答案

可以,但有一些浏览器限制。

创建证书,然后在证书存储中注册,或手动将其加载到Kestrel中,如下所示:

certificate.json

{
  "certificateSettings": {
    "fileName": "localhost.pfx",
    "password": "YourSecurePassword"
  }
}

并类似于这样使用它:

public class Program
{
    public static void Main(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddEnvironmentVariables()
            .AddJsonFile("certificate.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"certificate.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json", optional: true, reloadOnChange: true)
            .Build();

        var certificateSettings = config.GetSection("certificateSettings");
        string certificateFileName = certificateSettings.GetValue<string>("filename");
        string certificatePassword = certificateSettings.GetValue<string>("password");

        var certificate = new X509Certificate2(certificateFileName, certificatePassword);

        var host = new WebHostBuilder()
            .UseKestrel(
                options =>
                {
                    options.AddServerHeader = false;
                    options.Listen(IPAddress.Loopback, 443, listenOptions =>
                    {
                        listenOptions.UseHttps(certificate);
                    });
                }
            )
            .UseConfiguration(config)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>()
            .UseUrls("https://localhost:443")
            .Build();

        host.Run();
    }
}

摘自这篇好的博客帖子:https://www.humankode.com/asp-net-core/develop-locally-with-https-self-signed-certificates-and-asp-net-core

这篇关于ASP.NET Core 3.1Web API:是否可以使用https作为Windows服务自托管,并使用像IIS这样的证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆