无法使用 HTTPS 启动 ASP.NET 核心

Unable to start ASP.NET Core with HTTPS

我有一个 WPF 应用程序,它启动了一个 ASP.NET 核心 WEB API 应用程序。

当我使用这些配置启动 WEB API 项目作为启动项目时,它适用于 HTTPS。 但是,当我尝试从 WPF 环境启动此应用程序时,它不适用于 HTTPS。

配置:

  1. Web API configuration:

  1. In Startup.cs file:
public void ConfigureServices(IServiceCollection services)
        {

                services.AddMvc();

                services.Configure<MvcOptions>(options =>
                {
                    options.Filters.Add(new RequireHttpsAttribute());
                });
        }

The Main method looks like this:

public static void InitHttpServer()
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("https://localhost:44300/")
            //.UseApplicationInsights()
            .Build();

        host.Run();
    }

When I check the port using netstat command, it shows:

Postman says:

应用程序中操作方法上的调试器都没有被命中。

P.S。 : 当我还原 HTTPS 的更改并尝试使用 HTTP 时,它工作正常。

HTTP 的主要方法有不同的端口和none 上述配置更改。

当您在 Web 服务器设置中启用 SSL 时,您为 IIS 而不是您的应用程序启用了 SSL。当您从 Visual Studio 启动 Web API 时,其 运行 会在 IIS 后面作为反向代理服务。这就是为什么只有当您 运行 将它作为启动项目时才会获得 SSL。当您从 WPF 应用程序 运行 时,API 仅在 Kestrel 上 运行ning。

因此,要在 Kestrel 上启用 SSL,您需要添加一个证书,然后在设置 Kestrel 时将其传入。

var cert = new X509Certificate2("YourCert.pfx", "password");

var host = new WebHostBuilder()
    .UseKestrel(cfg => cfg.UseHttps(cert))
    .UseContentRoot(Directory.GetCurrentDirectory())
    .UseIISIntegration()
    .UseStartup<Startup>()
    .UseUrls("https://localhost:44300/")
    //.UseApplicationInsights()
    .Build();