Search code examples
c#apache.net-corekestrel

.NET Core 3.1 IHostBuilder Apache Hosting With Kestrel Program.cs Setup


I have a web application running on CentOS 7 with an Apache server used as a proxy for Kestrel. In my Program.cs file I'm using the below, which seems to work fine:

    public static void Main(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .Build();

        var host = new WebHostBuilder()
            .UseKestrel()
            .UseConfiguration(config)
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>()
            .UseUrls("http://localhost:5555")
            .Build();

        host.Run();
    }

But it looks like things with .NET Core have been updated recently, and I'm trying to use the IHostBuilder in the same way as below, which seems to work fine locally, but on the production server I'm getting the error "Proxy Error 502: The proxy server received an invalid response from an upstream server".

    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)            
            .ConfigureWebHostDefaults(webBuilder =>
            {                    
                webBuilder.UseKestrel();
                webBuilder.UseContentRoot(Directory.GetCurrentDirectory());
                webBuilder.UseConfiguration(new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddCommandLine(args).Build());
                webBuilder.UseUrls("https://localhost:5555");
                webBuilder.UseStartup<Startup>();
            });

I'm not sure if this has anything to do with the configuration of the domain on my server - which again works fine using the first example above - or if there's something else I need to do in either the Program.cs or Startup.cs that would fix this problem using IHostBuilder.

In the meantime I'm going to keep using what I have since it's working fine that way.

Thanks in advance to anyone who can help shed some light on this. And please let me know if there's any other information I can provide to help.


Solution

  • Wow... it was because the service running my web app is running on http but forces redirect to https. The issue was this line:

    webBuilder.UseUrls("https://localhost:5555");

    Needs to be this:

    webBuilder.UseUrls("http://localhost:5555");

    I also tested Xavier's solution, which also works. So thanks for offering up a solution.