0

I have an ASP.NET Core 2.2 application that contains the following code in its Program.cs file:

private static IWebHost BuildWebHost(string[] args)
{
    string appDir = Directory.GetCurrentDirectory();
    var webHostBuilder = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(appDir)
        // and a few more...
        .UseStartup<Startup>();

    Urls = webHostBuilder.GetSetting(WebHostDefaults.ServerUrlsKey);

    return webHostBuilder.Build();
}

Now I'm creating an ASP.NET Core 3.1 project and want to reuse as much as possible. Also, the older project will need to get upgraded one day, so I need to know how to modify the code then.

The new project looks like this:

public static IHostBuilder CreateHostBuilder(string[] args)
{
    string appDir = Directory.GetCurrentDirectory();
    var hostBuilder = Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

    Urls = hostBuilder.GetSetting(WebHostDefaults.ServerUrlsKey);

    return hostBuilder;
}

This shows an error because hostBuilder.GetSetting is not defined. I can't find anything similar or another solution to this. I also don't know where the original code came from.

How do I need to modify this code so that it can access its public URL, however that was configured?

ygoe
  • 14,805
  • 19
  • 92
  • 173

1 Answers1

0

Thanks to the comment by Crowcoder, I could find the solution to this. The following code works as expected. The WebHostBuilder is now packed away inside the HostBuilder.ConfigureWebHostDefaults method.

public static IHostBuilder CreateHostBuilder(string[] args)
{
    string appDir = Directory.GetCurrentDirectory();
    var hostBuilder = Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
            Urls = webBuilder.GetSetting(WebHostDefaults.ServerUrlsKey);
        });

    return hostBuilder;
}
ygoe
  • 14,805
  • 19
  • 92
  • 173