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.