Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to start ASP.NET Core with HTTPS

I have a WPF application, which starts a ASP.NET core WEB API application.

When I start the WEB API project as the startup project with these configurations, it works fine for HTTPS. But, when I try to launch this application from WPF environment, it's not working for HTTPS.

Configurations:

  1. Web API configuration:

enter image description here

  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:

enter image description here

Postman says:

enter image description here

Neither the debugger on the action method in the application is being hit.

P.S. : When I revert the changes for HTTPS and try use HTTP, it works fine.

The main method for HTTP has different port and none of the configuration changes mentioned above.

like image 817
XYZ Avatar asked Oct 29 '22 06:10

XYZ


1 Answers

When you enable SSL in the web server settings your enabling SSL for IIS not your application. When you launch the web API from Visual Studio its running behind IIS as a reverse proxy service. This is why you get SSL only when you run it as the startup project. When you run it from your WPF application the API is running on Kestrel only.

So to enable SSL on Kestrel you need to add a cert then pass it in when setting up 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();
like image 84
Travis Boatman Avatar answered Nov 15 '22 05:11

Travis Boatman