Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

ASP.NET Core Configuration

Introduction to ASP.NET Core Configuration

ASP.NET Core Configuration is stored in the format of name-value pairs, and it will be read during runtime from different parts of the application. Those name-value pairs are assembled into a multi-level hierarchy. ASP.NET Core supports various methods in Configuration. The configuration data comes from various sources like JSON, XML, INI, environment variables, command-line arguments, custom providers, and in-memory collection. The configuration system in ASP.NET Core is simplified from an older version of ASP.NET.

What is ASP.NET Core Configuration?

  • The ASP.NET Core Configuration is performed using configuration providers.
  • The configuration providers read the configuration data from key-value pairs by using the selection of various configuration sources like app settings and so on.
  • ASP.NET Core supports various configurations, it is stored in the name-value pairs, and it can be read during runtime from the applications; those name-value pairs are assembled into a multi-level hierarchy.

ASP.NET Core Web Apps Created

The namespace used by the older version is “System.Configuration” it can read XML configuration files like the web.config. The recent configuration model accessed to key/ value-based will be retrieved from different sources. In this ASP.NET Core, Solution Explorer, we can see the Startup.cs file. Like that we have worked with the previous version of ASP.NET Core, we can able to see a global.asax file; it was in one place in which you can code to execute during startup of the web application.

  • Web.Config file contains the entire configuration parameters your application requires for execution.
  • In ASP.NET Core, the configuration and startup code is loaded from Startup.cs.
  • The file contains the Startup class in it, and in this class, you can configure the configuration sources and also can configure the application.

The default implementation in the Startup.cs file:

Code:

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 SampleProgram
{
public class Startup
{
//this method is called during the runtime, by using the method we add the services to the container
public void ConfigureServices(IServiceCollection services)
{
}
//this method is called during the runtime, by using the 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("WELCOME !");
});
}
}
}

In this Startup class, we mostly work on the two methods; the Configure method class is that where you can build the HTTP processing pipeline.

  • It defines how the application responds to the requests. For example, in the above code, it says the “WELCOME,” if we require behaving the application differently, we need to alter the pipeline by including the additional codes in Configure method.
  • If we want to serve the static file like the index.html file, we have to add the codes to the Configure method. We can also include the route requests or error page to the ASP.NET controller by adding codes to Configure method.
  • In the Startup class, there will be ConfigureService() method, it helps you to configure the components of the application.

Using Files for ASP.NET Core Configuration

  • The using files for ASP.NET Core Configuration are Web.Config, which is a file that ASP.NET Core Module and IIS read to configure an app hosted with IIS.
  • The Microsoft .NET Framework and ASP.NET use the XML formatted .config files to configure the applications.
  • The configuration data comes from various sources like JSON, XML, INI, environment variables, command-line arguments, custom providers, and in-memory collection.
  • The configuration system in ASP.NET Core is simplified from an older version of ASP.NET.

Example of ASP.NET Core Configuration

Different examples are mentioned below:

ASP.NET Core supports various methods in Configuration. It is stored in the format of name-value pairs, and it will be read during runtime from different parts of the application. Those name-value pairs are assembled into a multi-level hierarchy.

Let’s see the example of reading the configuration using the JSON provider.

ASP.NET Core Configuration is performed using configuration providers. The configuration providers read the configuration data from key-value pairs by using the selection of various configuration sources like app settings.

Example of appsetting.json file.

Code:

appsetting.json
{
"status" : "Status is to read from appSettings.json file", "ConnectionStrings":
{
"DefaultConnection": "Server=.\\sqlexpress;Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}

We need to include the libraries as a dependency for reading the JSON configuration file; they are “Microsoft.Extensions.Configuration” and “Microsoft.Extensions.Configuration.Json.”

Dependency section includes the two following package.json:

  • “Microsoft.Extensions.Configuration”:”1.0.0″
  • “Microsoft.Extensions.Configuration.Json”:”1.0.0″

The method AddJsonFile of the “JsonConfigurationExtensions” class is used for building the JSON file. To get the configuration value by using the key name, we can retrieve the configuration value in hierarchical structure use a “:” (separated key) from the root of the hierarchy. Here we have to get the value for “DefaultConnection”, then key becomes “ConnectionStrings:DefaultConnection”.

Following sample program for Startup:

Code:

Startup.cs:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace SampleApplication
{
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appSettings.json");
Configuration = builder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
app.Run(context =>
{
var status = Configuration["status"];
var connectionString = Configuration["ConnectionStrings:DefaultConnection"];
context.Response.WriteAsync("Default Connection: " + connectionString);
context.Response.WriteAsync("
");
return context.Response.WriteAsync("Status: " + status);
});
}
}
}

Output:

Retrieve the configuration data at controller:

The latest version of ASP.NET has built-in support for dependency injection; using DI, we inject the configuration value to the controller. For example, to include the singleton service of the specified type with an instance of service by using the AddSingleton method of ServiceCollecctionServiceExtensions class.

Code:

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton(Configuration);
}

HomeController.cs:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
public class HomeController : Controller
{
IConfiguration _configuration;
public HomeController(IConfiguration configuration)
{
_configuration = configuration;
}
[Route("home/index")] public IActionResult Index()
{
ViewBag.connectionstring = _configuration["ConnectionStrings:DefaultConnection"];
return View();
}
}

Output:

Conclusion

In this article, we saw Configuration in ASP.NET Core, which provides the flexible configuration method that supports various ways to work with configuration such as in-memory, environmental variables, file-based, etc. It also maintains the options model so that we can strongly inject the settings into the application.

Recommended Articles

This is a guide to ASP.NET Core Configuration. Here we discuss the introduction, ASP.NET core web apps created, and examples, respectively. You may also have a look at the following articles to learn more –

  1. Validation in ASP.NET
  2. ASP.NET security
  3. ASP.NET life cycle
  4. ASP.NET Web Controls

The post ASP.NET Core Configuration appeared first on EDUCBA.



This post first appeared on Best Online Training & Video Courses | EduCBA, please read the originial post: here

Share the post

ASP.NET Core Configuration

×

Subscribe to Best Online Training & Video Courses | Educba

Get updates delivered right to your inbox!

Thank you for your subscription

×