How can I add a custom JSON file into IConfiguration?
As of ASP.NET Core 5.0 it is as simple as adding a call to ConfigureAppConfiguration() in the call to CreateDefaultBuilder(args) inside Program.cs like so:
From
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
to
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("CustomSettings.json", optional: false, reloadOnChange: false);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
For .Net Core 2.2, you need to modify Program.cs:
Before
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
After
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
//This is how you attach additional JSON files
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.AddJsonFile("customSettings.json", optional: false, reloadOnChange: false);
})
//End of update
.UseStartup<Startup>();
For the latest amendments and to add other kinds of custom settings, please refer to Microsoft documentation at the following article.
You can do this by using the Options pattern:
On ASP.NET Core 2, register the config file on Program.cs
public class Program
{
public static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
// custom config file
.AddJsonFile("myappconfig.json", optional: false, reloadOnChange: false)
.Build();
BuildWebHost(args, configuration).Run();
}
public static IWebHost BuildWebHost(string[] args, IConfiguration config) =>
WebHost.CreateDefaultBuilder(args)
.UseConfiguration(config)
.UseStartup<Startup>()
.Build();
}
Create a class that matches with your config file:
public class MyAppConfig
{
public string SomeConfig { get; set; }
public int NumberConfig { get; set; }
}
Register it on ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MyAppConfig>(Configuration);
}
Then, just access it in your Controller:
[Route("api/[controller]")]
public class ValuesController : Controller
{
private readonly MyAppConfig _appConfig;
public ValuesController(IOptions<MyAppConfig> optionsAccessor)
{
if (optionsAccessor == null) throw new ArgumentNullException(nameof(optionsAccessor));
_appConfig = optionsAccessor.Value;
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return _appConfig.SomeConfig;
}
}
If you are not in ASP.NET Core 2 yet, the process is almost the same. You just need to add the custom config file on Startup.cs
. The rest is basically the same.