Managing configuration settings is crucial for any application, including Web APIs. Separating configuration from code allows for cleaner codebases, easier maintenance, and flexibility to change settings without redeploying your application. This guide will walk you through adding custom configuration to a .NET 8 Web API application.
Prerequisites
- .NET 8 SDK installed on your machine.
- A basic .NET 8 Web API Application. You can create one using the command:
dotnet new webapi -o MyWebApiApp
Step 1: Understanding the Default Configuration
When you create a new Web API project, appsettings.json
and appsettings.Development.json
files are included by default. The appsettings.json
file is used to store configuration settings in JSON format, which the application reads at runtime.
Step 2: Adding Custom Configuration Sections
Let's add a custom configuration section to the appsettings.json
file. Open appsettings.json
and add the following:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ApiSettings": {
"TwitterApiKey": "your-api-key",
"TwitterApiSecret": "your-api-secret",
"BearerToken": "your-bearer-token"
}
}
This adds a new section called ApiSettings
where you can store your API credentials.
Step 3: Create a Strongly-Typed Configuration Class
To access the ApiSettings
section in a strongly-typed manner, create a new class that matches the structure of the configuration section.
Create a new file ApiSettings.cs
in your project:
namespace MyWebApiApp
{
public class ApiSettings
{
public string TwitterApiKey { get; set; }
public string TwitterApiSecret { get; set; }
public string BearerToken { get; set; }
}
}
Step 4: Register the Configuration in Program.cs
In .NET 8, the Program.cs
file uses the minimal hosting model. You'll need to modify it to register your configuration class.
Open Program.cs
and modify it as follows:
// Bind ApiSettings and add it to the services collection
builder.Services.Configure<ApiSettings>(builder.Configuration.GetSection("ApiSettings"));
It should look like this:
using Microsoft.Extensions.Configuration;
using MyWebApiApp;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Bind ApiSettings and add it to the services collection
builder.Services.Configure<ApiSettings>(builder.Configuration.GetSection("ApiSettings"));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
This code binds the ApiSettings
section of the configuration to the ApiSettings
class and registers it with the dependency injection (DI) container.
Step 5: Access Configuration in Controllers or Services
Now that the configuration is registered, you can inject it into your controllers or services.
Injecting into a Controller
Open the WeatherForecastController.cs
(or create a new controller) and modify it to use IOptions<ApiSettings>
:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace MyWebApiApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class TwitterController : ControllerBase
{
private readonly ApiSettings _apiSettings;
public TwitterController(IOptions<ApiSettings> apiSettings)
{
_apiSettings = apiSettings.Value;
}
[HttpGet("apikey")]
public IActionResult GetApiKey()
{
return Ok(new
{
TwitterApiKey = _apiSettings.TwitterApiKey,
TwitterApiSecret = _apiSettings.TwitterApiSecret,
BearerToken = _apiSettings.BearerToken
});
}
}
}
Injecting into a Service
If you prefer to keep your controllers thin, you can create a service class:
Create a Service Interface and Class
Create a new interface ITwitterService.cs
:
namespace MyWebApiApp.Services
{
public interface ITwitterService
{
string GetApiKey();
string GetApiSecret();
string GetBearerToken();
}
}
Create the implementation TwitterService.cs
:
using Microsoft.Extensions.Options;
namespace MyWebApiApp.Services
{
public class TwitterService : ITwitterService
{
private readonly ApiSettings _apiSettings;
public TwitterService(IOptions<ApiSettings> apiSettings)
{
_apiSettings = apiSettings.Value;
}
public string GetApiKey() => _apiSettings.TwitterApiKey;
public string GetApiSecret() => _apiSettings.TwitterApiSecret;
public string GetBearerToken() => _apiSettings.BearerToken;
}
}
Register the Service in Program.cs
Add the service to the DI container:
// ...
builder.Services.AddSingleton<ITwitterService, TwitterService>();
// ...
Modify the Controller to Use the Service
Update TwitterController.cs
:
using Microsoft.AspNetCore.Mvc;
using MyWebApiApp.Services;
namespace MyWebApiApp.Controllers
{
[ApiController]
[Route("[controller]")]
public class TwitterController : ControllerBase
{
private readonly ITwitterService _twitterService;
public TwitterController(ITwitterService twitterService)
{
_twitterService = twitterService;
}
[HttpGet("apikey")]
public IActionResult GetApiKey()
{
return Ok(new
{
TwitterApiKey = _twitterService.GetApiKey(),
TwitterApiSecret = _twitterService.GetApiSecret(),
BearerToken = _twitterService.GetBearerToken()
});
}
}
}
Step 6: Run and Test the Application
Run your application using:
dotnet run
Navigate to https://localhost:<port>/swagger
to access the Swagger UI. You should see your TwitterController
and the GetApiKey
endpoint.
Try executing the GetApiKey
endpoint to see your configuration values returned.
Step 7: Secure Your Sensitive Data
Important: Never store sensitive information like API keys or secrets in plain text within appsettings.json
, especially in production environments.
Using User Secrets for Development
For development, you can use the Secret Manager to store sensitive data.
Run the following command in your project directory:
dotnet user-secrets init
Add secrets using:
dotnet user-secrets set "ApiSettings:TwitterApiKey" "your-api-key"
dotnet user-secrets set "ApiSettings:TwitterApiSecret" "your-api-secret"
dotnet user-secrets set "ApiSettings:BearerToken" "your-bearer-token"
These secrets will be stored securely on your machine and won't be checked into source control.
Modifying Program.cs
to Include User Secrets
When in development mode, the configuration builder automatically includes user secrets. Ensure your Program.cs
includes builder.Configuration
as shown:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.Configure<ApiSettings>(builder.Configuration.GetSection("ApiSettings"));
// ...
Conclusion
By following these steps, you've successfully added custom configuration to your .NET 8 Web API application. This setup allows you to manage your application settings efficiently while keeping your code clean and maintainable. Remember to secure sensitive information appropriately, especially in production environments.
Happy coding!
References:
This is a continuation from:
https://dev.to/iamrule/add-your-appsettingsjson-to-a-c-console-application-5gd6
Top comments (0)