0

In the new ASP.NET Core 6 minimal hosting model, how do I set the webroot from the usual appsettings.{Environment}.json files (and all the other usual configuration sources the hosting builder sets up by default)?

When I do it via builder.WebHost.UseWebRoot like in the below example I will get an exception.

var builder = WebApplication.CreateBuilder(args);

// setup a default value in case it's not set in appsettings.{Environment}.json
builder.Configuration.AddInMemoryCollection(
    new Dictionary<string, string?>
    {
        ["webroot"] = "website",
    });

// NotSupportedException:
builder.WebHost
    .UseWebRoot(builder.Configuration.GetValue<string>("webroot")!);

var app = builder.Build();

app.UseStaticFiles();

app.Run();

This is the exception I get:

System.NotSupportedException: The web root changed from "C:\source\MyServer\bin\Debug\net8.0" to "C:\source\MyServer\website". Changing the host configuration using WebApplicationBuilder.WebHost is not supported. Use WebApplication.CreateBuilder(WebApplicationOptions) instead.

But when I change as way suggested in the exception text, I cannot use the pre-built builder.Configuration as the source because the builder is not yet available.

var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    Args = args,
    WebRootPath = builder.Configuration.GetValue<string>("webroot") // does not compile
});

// setup a default value in case it's not set in appsettings.{Environment}.json
builder.Configuration.AddInMemoryCollection(
    new Dictionary<string, string?>
    {
        ["webroot"] = "website"
    });

var app = builder.Build();

app.UseStaticFiles();

app.Run();

How can I use the default appsettings.{Environment}.jon (and all the other usual configuration sources the builder sets up by default) as the source for the webroot path.

bitbonk
  • 48,890
  • 37
  • 186
  • 278

1 Answers1

1

Do you want a configuration like this:

var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
    Args = args,
    WebRootPath = WebApplication.CreateBuilder(args).Configuration.GetValue<string>("webroot") != null ? WebApplication.CreateBuilder(args).Configuration.GetValue<string>("webroot") : "website"
});
Console.WriteLine($"WebRootPath: {builder.Environment.WebRootPath}");

Test Result:

enter image description here

Chen
  • 4,499
  • 1
  • 2
  • 9