In this blog, I am going to show you the AppSetting configuration in ASP.NET Core Application.
In ASP.NET Core Application, all the Application settings are now located in appsettings.json file instead of app.config/web.config file.
Here is what the default appsettings.json file looks like, though I have also added an AppSettings section, as shown below.
Configure Startup.cs
Write the highlighted line of code given below inside ConfigureServices method of Startup.cs file.
- services.Add(ServiceDescriptor.Singleton<IConfiguration>(Configuration));
ConfigureServices method gets called by the runtime. Usually this method is to add the Services to the container.
Screenshot for reference is given below.
Now, read the Application settings from appsettings.json file in ASP.NET Core Application's controller, as shown below.
- using Microsoft.Extensions.Configuration;
- public class TestController: Controller
- {
- private IConfiguration m_configuration;
- string fileSource, fileDestination = "";
- public TestController(IConfiguration configruation) {
- Initialize(configruation);
- }
- private void Initialize(IConfiguration configruation) {
- m_configuration = configruation.GetSection("AppSettings");
- fileSource = m_configuration["FileSource"];
- fileDestination = m_configuration["FileDestination"];
- }
- public string Get() {
- -- -- -- -- -- -- -
- -- -- -- -- -- -- -
- -- -- -- -- -- -- --
- }
- }