Reputation: 17527
I'm updating my ASP.Net Core project from RC1 to the recently released RC2. One problem I am facing is loading the config.json
file into the configuration object in Startup.cs
.
My project fails to start and throws the System.IO.FileNotFound
exception when it fails to find config.json
.
Here's the working code from RC1
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
Configuration = new ConfigurationBuilder()
.AddJsonFile("Settings/config.json")
.AddEnvironmentVariables()
.Build();
}
Here's the almost identical code in RC2, which does not work. Note that I've moved the config.json
file up a level just-in-case it was folder hierarchies that were causing the failure.
public Startup(IHostingEnvironment env)
{
Configuration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("config.json")
.AddEnvironmentVariables()
.Build();
}
(N.B. I've tried with and without the SetBasePath
call.)
One option is to replace .AddJsonFile("config.json")
with these two lines
.AddJsonFile("config.json", optional: true, reloadOnChange: true)
.AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
That does prevent the System.IO.FileNotFound
exception but only by making the file load optional, it still seems to fail to load.
To debug what is happening I've added a FileInfo("config.json")
and the file exists. I've tried using the full name from that FileInfo
object and I still get the exception.
How do I load the config.json
in RC2, or how do I diagnose its failure to load?
Upvotes: 0
Views: 363
Reputation: 49769
You should add WebHostBuilderExtensions.UseContentRoot
method call before building IWebHost
instance.
Example:
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
Upvotes: 3