We use configuration suppliers in ASP.NET Core to load configuration information into our software from a number of configuration sources. These suppliers can learn configuration information from command line arguments, atmosphere variables, JSON or XML information, databases, Azure Key Vault, and different sources—together with your individual customized sources.
The ASP.NET Core configuration system includes a set of courses that make it simpler to handle the configuration settings of your software. This method is light-weight and extensible, and it offers a constant strategy to retailer and retrieve configuration settings for all ASP.NET Core functions.
For customized configuration sources, you’ll be able to create your individual customized configuration supplier in ASP.NET Core and connect it to the configuration system. A customized configuration supplier might help you to scale back the complexity concerned in loading configuration metadata from customized configuration sources or exterior sources.
This text presents a dialogue on how we will create a customized configuration supplier in ASP.NET Core 6. To work with the code examples offered on this article, you need to have Visible Studio 2022 put in in your system. In case you don’t have already got a replica, you’ll be able to obtain Visible Studio 2022 right here.
Create an ASP.NET Core 6 Net API undertaking in Visible Studio 2022
First off, let’s create an ASP.NET Core undertaking in Visible Studio 2022. Following these steps will create a brand new ASP.NET Core 6 Net API undertaking in Visible Studio 2022:
- Launch the Visible Studio 2022 IDE.
- Click on on “Create new undertaking.”
- Within the “Create new undertaking” window, choose “ASP.NET Core Net API” from the checklist of templates displayed.
- Click on Subsequent.
- Within the “Configure your new undertaking” window, specify the title and site for the brand new undertaking.
- Optionally test the “Place resolution and undertaking in the identical listing” test field, relying in your preferences.
- Click on Subsequent.
- Within the “Further Info” window proven subsequent, choose .NET 6.0 because the goal framework from the drop-down checklist on the prime. Depart the “Authentication Kind” set to “None” (default).
- Be sure that the test containers “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Help” are unchecked as we received’t be utilizing any of these options right here.
- Click on Create.
We’ll use this ASP.NET Core 6 Net API undertaking to create a customized configuration supplier within the subsequent sections of this text.
Creating configuration suppliers in ASP.NET Core 6
A configuration supplier is usually a C# class that may retrieve configuration information from a supply (a file, a database, an exterior API, and many others.) and make it obtainable to the appliance. There are lots of built-in configuration suppliers in ASP.NET Core together with JSON, XML, and database suppliers. Nevertheless, you can too create your customized configuration supplier if it is advisable.
To create a customized configuration supplier, you need to create a category that extends the ConfigurationProvider class. Then, it is advisable override the Load() methodology to load the configuration information from wherever it’s saved and return the information as a key-value dictionary.
Upon getting created your customized configuration supplier, you’ll be able to register it with ASP.NET Core by including it to the companies assortment within the Program.cs file.
Let’s now get began constructing a customized configuration supplier in ASP.NET 6 Core. The ultimate resolution will comprise the next information:
- SecurityMetadata.cs
- CustomConfigurationSource.cs
- CustomConfigurationProvider.cs
- CustomConfigurationExtensions.cs
- CustomConfigurationController.cs
We’ll find out about every of those information within the sections that observe. As well as, we may even write code within the Program.cs file so as to add the configuration supplier and configuration supply to the default configuration system of the ASP.NET Core runtime. The Resolution Explorer window of the finished software ought to seem as proven in Determine 1 above.
Create a category for safety metadata in ASP.NET Core 6
We’ll retailer API keys and API secrets and techniques in a .json file and skim it within the software we’ll be constructing right here. We’ll not be utilizing any of those keys for authenticating or authorizing requests on this instance.
API keys and API secrets and techniques are each used to authenticate entry to an API. The primary distinction is that API keys are public and may be accessed by anybody, whereas API secrets and techniques are non-public and will by no means be shared. An API secret is an identifier that permits you to work together with an API in a safe method.
API keys are used to limit who can use an software and what they’ll do with it; i.e., they’re used to authenticate and authorize requests. API secrets and techniques are used to retailer delicate data in your app. You too can use API secrets and techniques to generate checksums and to encrypt and decrypt information.
Create a category named SecurityMetadata in a file having the identical title with a .cs extension and enter the next code.
  public class SecurityMetadata
   {
       public string ApiKey { get; set; }       Â
       public string ApiSecret { get; set; }
   }
Create a category for a configuration supply in ASP.NET Core 6
Subsequent, we’ll create a configuration supply to initialize our customized configuration supplier. To do that, create a brand new .cs file named CustomConfigurationSource and provides it the next code.
   public class CustomConfigurationSource : IConfigurationSource
   {
       public IConfigurationProvider Construct(IConfigurationBuilder builder)
       {
           return new CustomConfigurationProvider();
       }
   }
Your customized configuration supply should implement the IConfigurationSource interface. The IConfigurationSource interface comprises the Construct methodology the place you need to invoke your customized configuration supplier.
Create a customized configuration supplier in ASP.NET Core 6
To learn configuration data from an exterior information supply, you need to implement your customized configuration supplier. Your customized configuration supplier is a standard C# class that extends the Microsoft.Extensions.Configuration.ConfigurationProvider summary class and overrides the Load() methodology as proven within the code itemizing given beneath.
   public class CustomConfigurationProvider :
   Microsoft.Extensions.Configuration.ConfigurationProvider
   {
       public override void Load()
       {
           var textual content = File.ReadAllText(@"D:SecurityMetadata.json");
           var choices = new JsonSerializerOptions
           { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
           var content material = JsonSerializer.Deserialize<SecurityMetadata>
          (textual content, choices);
           if (content material != null)
           {
               Information = new Dictionary<string, string>
               {
                   {"ApiKey", content material.ApiKey},
                   {"ApiSecret", content material.ApiSecret}
               };
           }
       }
   }
Be aware how the ApiKey and ApiSecret are being saved within the dictionary occasion named Information.
Create a customized configuration extensions class in ASP.NET Core 6
We’ll now create an extension methodology that can create an occasion of the CustomConfigurationSource class and return it.
   public static class CustomConfigurationExtensions
   {
       public static IConfigurationBuilder AddSecurityConfiguration
       (this IConfigurationBuilder builder)
       {
           return builder.Add(new CustomConfigurationSource());
       }
   }
Add the customized configuration supply to Program.cs in ASP.NET Core 6
Now, enter the next line of code within the Program.cs file so as to add the customized configuration supply to the gathering of configuration suppliers.
builder.Configuration.AddSecurityConfiguration();
The whole code itemizing of the Program.cs file is given beneath to your reference.
utilizing CustomConfigurationProvider;
var builder = WebApplication.CreateBuilder(args);
// Add companies to the container.
builder.Configuration.AddSecurityConfiguration();
builder.Providers.AddControllers();
builder.Providers.AddEndpointsApiExplorer();
builder.Providers.AddSwaggerGen();
var app = builder.Construct();
// Configure the HTTP request pipeline.
if (app.Surroundings.IsDevelopment())
{
   app.UseSwagger();
   app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
Create a customized configuration controller in ASP.NET Core 6
Lastly, create a brand new API controller named CustomConfigurationController and exchange the default generated code with the next code itemizing.
   [Route("api/[controller]")]
   [ApiController]
   public class CustomConfigurationController : ControllerBase
   {
       non-public readonly IConfiguration _configuration;
       public CustomConfigurationController(IConfiguration configuration)
       {
           _configuration = configuration;
       }
       [HttpGet]
       public IActionResult Get()
       {
           var metadata = new SecurityMetadata
           {
               ApiKey = _configuration["ApiKey"],
               ApiSecret = _configuration["ApiSecret"]
           };
           return Okay(metadata);
       }
   }
Be aware how the IConfiguration occasion is injected within the constructor of the CustomConfigurationController class.
In case you now run the appliance and hit the HttpGet endpoint of the CustomConfigurationController, you need to see the configuration information being returned after it’s learn from the .json file within the file system. To test this, set a breakpoint within the HttpGet motion methodology of the CustomConfigurationController as proven in Determine 2 beneath.
On this submit we’ve applied a customized configuration supplier that may learn configuration information from a .json file. Be aware that we’ve executed the appliance instantly from the Visible Studio 2022 IDE and set a breakpoint to confirm if the configuration information is being returned correctly. Alternatively, you might run the appliance utilizing Postman, Fiddler, or the Swagger UI.
Copyright © 2022 IDG Communications, Inc.