I'd like to provide the content root to be set via command line so I can start the application reading data from different directories, ex: dotnet run --content-root="F:/any/path"
According to the documentation IHostingEnvironment.ContentRootPath
Property
Gets or sets the absolute path to the directory that contains the application content files.
Creating a default web api via dotnet new webapi
. This is the default Program.cs:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
In Startup.cs, including the code env.ContentRootPath = @"F:/foo/bar/";
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
env.ContentRootPath = @"F:/foo/bar/";
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Running the application:
C:johndoe> dotnet run
Building...
warn: Microsoft.AspNetCore.Server.Kestrel[0]
Overriding address(es) 'https://localhost:5001, http://localhost:5000'. Binding to endpoints defined in UseKestrel() instead.
info: Microsoft.Hosting.Lifetime[0]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: C:johndoe
The content root path setting is ignored. The hard-coded assignment doesn't change anything.
question from:
https://stackoverflow.com/questions/65891646/how-to-set-asp-net-content-root-path 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…