net core 3.1 manually bind configuration from other json file
- User
net core 3.1 manually bind configuration from other json file
- Assistant
net core 3.1 manually bind configuration from other json file
In ASP.NET Core 3.1, you can manually configure your application to read from a JSON configuration file other than appsettings.json. You can do this in the CreateHostBuilder method of your Program.cs file. Below are the steps and an example of how to accomplish this.
First, create a custom JSON file in your project. For example, you could create a file named customsettings.json with the following content:
{
"CustomSetting": "This is a custom setting value"
}
You need to modify the Program.cs file to add the custom configuration file. Here’s how you can do it:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, config) =>
{
// Clear default configuration sources if needed
// config.Sources.Clear();
// Add the custom JSON file
config.AddJsonFile("customsettings.json", optional: true, reloadOnChange: true);
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
customsettings.json).true, the application will not throw an error if the file does not exist.true, the configuration will automatically reload if the JSON file changes.Now that you have added the custom configuration file, you can access the configuration settings throughout your application. Here’s how you can access your custom setting in a controller:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
public class HomeController : Controller
{
private readonly IConfiguration _configuration;
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
public IActionResult Index()
{
var customSettingValue = _configuration["CustomSetting"];
ViewBag.CustomSetting = customSettingValue;
return View();
}
}
This setup allows you to manually bind a configuration from a JSON file other than the default appsettings.json. With this, you can keep your configuration organized and possibly separate for different environments or purposes. You can now run your ASP.NET Core 3.1 application, and it will read the settings from your customsettings.json file as well.
Not yet included in a published release.