Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Implement, Access and Retrieve Configuration in ASP.NET Core

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 1.40k
    Comment on it

     

    In previous versions of ASP.NET the common file web.config was used for configuration. But now Asp.Net Core provides a new way for declaring and accessing configuration settings. Prior to ASP.NET Core for accessing configuration settings, in web.config file inside the appSettings node, add the settings that need to be accessed.

     

    <appSettings>
        <add key="SmtpServer" value="0.0.0.1" />
        <add key="SmtpUserName" value="test@test.com" />
        <add key="SmtpPort" value="25" />
        <!-- More Settings -->
    </appSettings>

     

    Above settings work as a key-value dictionary. Now, to access these values "ConfigurationManager" class is used:-

      

    ConfigurationManager.AppSettings["SmtpUserName"];

     

    In Asp.Net Core there is a startup class which not only configure the application but also configure the configuration sources. Configuration settings can be read from different sources like XML, JSON and INI files.

     

    Default implementation of startup.cs file is :-

     

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Threading.Tasks; 
    using Microsoft.AspNetCore.Builder; 
    using Microsoft.AspNetCore.Hosting; 
    using Microsoft.AspNetCore.Http; 
    using Microsoft.Extensions.DependencyInjection; 
    using Microsoft.Extensions.Logging;  
    
    namespace AspNetCoreAppDemo { 
       public class Startup { 
          // This method gets called by the runtime.
          // Use this method to add services to the container. 
          public void ConfigureServices(IServiceCollection services) { 
          }  
          
          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
          public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { 
             loggerFactory.AddConsole();  
             
             if (env.IsDevelopment()) { 
                app.UseDeveloperExceptionPage(); 
             }  
             app.Run(async (context) => { 
                await context.Response.WriteAsync("Hello Asp Net Core Demo Application!"); 
             }); 
          } 
       } 
    } 

     

    When this application runs it provides following output :-

     

     

    Example of accessing configuration settings from json file.

     

    In case of Asp.net core web application mvc template project "appsettings.json" is provided by default where user can enter configuration data. But in case of Asp.net core web application empty template project an appsettings json file is to be created by user. In the Solution Explorer, right-click on project node and select Add → New Item. Then, in left pane select Installed -> Code and then from middle pane select option JSON File. Name this json file as "AppSettings.json" and click on add button to add the file. Now startup class can read text from above created "AppSettings.json" file instead of having hard-coded string for every response. For using configuration settings in startup class install "Microsoft.Extensions.Configuration"  nuget package.

     

    Manipulate "AppSettings.json" file and add following text to it.

     

    {
     "message": "Hello, Asp.Net Core Demo Application! This message is from configuration file..."
    }


     

    Below is the implementation of startup class in order to access text string from "AppSettings.json" file.

     

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Configuration;
    using System.IO;
    
    namespace AspNetCoreAppDemo
    {
        public class Startup
        {
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
            }
    
            public Startup()
            {
                var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("AppSettings.json");
                Configuration = builder.Build();
            }
    
            public IConfiguration Configuration { get; set; }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
    
                app.Run(async (context) =>
                {
                    var msg = Configuration["message"];
                    await context.Response.WriteAsync(msg);
                });
            }
        }
    }

     

    Output :-

     

     

    Following scenarios are taken for Asp.net core web application mvc template project :-

     

    •  Retrieve Configuration Data at Controller

     

    For accessing configuration data in controller use built-in support dependency injection by which the configuration data can be injected to the controller. In startup class within "ConfigureServices" method add a singleton service of specified type by using AddSingleton method of ServiceCollectionServiceExtensions class.

     

    Example :-

     

    content of "appSettings.json"

     

    {
     "message": "Hello, Asp.Net Core Demo Application! This message is from configuration file for controller..."
    }

     

    Startup.cs class

     

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using System.IO;
    
    namespace AspNetCoreAppDemo
    {
        public class Startup
        {
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddApplicationInsightsTelemetry(Configuration);
                services.AddMvc();
                services.AddSingleton<IConfiguration>(Configuration);
            }
    
            public Startup()
            {
                var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
                Configuration = builder.Build();
            }
    
            public IConfiguration Configuration { get; set; }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                app.UseApplicationInsightsExceptionTelemetry();
                app.UseStaticFiles();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }
    

     

    HomeController

     

    namespace AspNetCoreAppDemo.Controllers
    {
        public class HomeController : Controller
        {
            IConfiguration config;
            public HomeController(IConfiguration configuration)
            {
                config = configuration;
            }
    
            public IActionResult Index()
            {
                ViewBag.Message = config["message"];
                return View();
            }
    	}
    }

     

    Index.cshtml

     

    @{
        ViewData["Title"] = "Home Page";
    }


    Output :-

     

     

     

    • Get Configuration object using options pattern

     

    A group of related settings can be represented via custom option classes enabled by options pattern. Creating a custom option class for working with the configuration data is the key advantage of new configuration model. The Custom option class must contain read-write public property defined for each setting and this class should not take any parameters.


    Example of custom option class :-

     

    Create a class "SmtpConfig" inside Models folder and define properties as follows:-

     

    namespace AspNetCoreAppDemo.Models
    {
        public class SmtpConfig
        {
            public string Server { get; set; }
            public string UserName { get; set; }
            public string Password { get; set; }
            public int Port { get; set; }
        }
    }
    

     

    Alter "appsettings.json" file and add following data :-

     

    {
      "Smtp": {
        "Server": "0.0.0.2",
        "UserName": "test@test.com",
        "Password": "12345678", 
        "Port": "25"
      },
      "message": "Hello, Asp.Net Core Demo Application! This message is from configuration file for controller..."
    }

     

    To access this section of configuration data "ConfigureServices" method is altered by adding configure service of specified type.

     

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using System.IO;
    using AspNetCoreAppDemo.Models;
    
    namespace AspNetCoreAppDemo
    {
        public class Startup
        {
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddApplicationInsightsTelemetry(Configuration);
                services.AddMvc();
                services.Configure<SmtpConfig>(Configuration.GetSection("Smtp"));  //to access Smtp section           
                services.AddSingleton<IConfiguration>(Configuration);
            }
    
            public Startup()
            {
                var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
                Configuration = builder.Build();
            }
    
            public IConfiguration Configuration { get; set; }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                app.UseApplicationInsightsExceptionTelemetry();
                app.UseStaticFiles();
    
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }

     

    For using above configuration data in mvc controller use interface IOptions<TOptions> accessor service,through which Options are injected into our application.

     

        public class HomeController : Controller
        {
            IConfiguration config;
            public SmtpConfig SmtpConfig { get; }
            public HomeController(IConfiguration configuration, IOptions<SmtpConfig> smtpConfig)
            {
                config = configuration;
                SmtpConfig = smtpConfig.Value;
            }
    	}

     

    Running above application(output) :-

     

     

     

     

     

    Configuring Multiple Environments (Asp.net core web application empty template project)

     

    Sometimes situation arises when different configuration values is to be used for different environments(staging, production, development). We can create separate json file for different environment like for development a file named "AppSettings.development.json". All configuration setting for development environment are contained within this file. The current environment of application can known through environment variable called Hosting:Environment. This variable is found via Right click on project node -> properties -> in left pane select "Debug" mode -> in middle pane "Environment Variables" option appear which can be altered according to need.

     

    Content of AppSettings.development.json

     

    {
      "message": "Hello, this message is from development configuration file..."
    }

     

    To access configuration values based on environment startup class is altered as follows :-

     

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Configuration;
    using System.IO;
    
    namespace AspNetCoreMiddleware
    {
        public class Startup
        {
            // This method gets called by the runtime. Use this method to add services to the container.
            // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddSingleton<IConfiguration>(Configuration);
            }
    
            public Startup(IHostingEnvironment env)
            {
                var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("AppSettings.json")
                                .AddJsonFile($"AppSettings.{env.EnvironmentName}.json", optional: true).AddEnvironmentVariables();
                Configuration = builder.Build();
            }
    
            public IConfiguration Configuration { get; set; }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
    
                app.Run(async (context) =>
                {
                    var msg = Configuration["message"];
                    await context.Response.WriteAsync(msg);
                });
            }
        }
    }


     

    Now in above code first read "AppSettings.json" file and then based on the environment read additional AppSettings file. If file exists the values of properties are overridden.

     

    Output :-

     

     

    How to Implement, Access and Retrieve Configuration in ASP.NET Core

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: