Tags
Problem
When publishing a dotnet core 3.0 application with PublishSingleFile=true an exception is thrown on startup because it can't find appsettings.json
Unhandled exception. System.IO.FileNotFoundException: The configuration file 'appsettings.json' was not found and is not optional.
Solution
When publishing as a single file the application is extracted and run from a temporary directory that is separate from the application.exe you run. To make it look for appsettings.json in the correct location you have to set the base path when building the configuration.
The following will return the correct base patch depending on whether you are running in development or production mode.
private static string GetBasePath()
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var isDevelopment = environment == Environments.Development;
if(isDevelopment)
{
return Directory.GetCurrentDirectory();
}
using var processModule = Process.GetCurrentProcess().MainModule;
return Path.GetDirectoryName(processModule?.FileName);
}
Then use GetBasePath() to set the base path before adding the json file
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.SetBasePath(GetBasePath());
config.AddJsonFile("appsettings.json", optional: false);
})
.UseStartup<Startup>();
}
About Sean Nelson
I like codes and stuff.
|
10 comments