Abayomi Ogunnusi
Posted on December 11, 2023
IOptions Pattern in ASP.NET Core in 4 Steps
This is a pattern that allows you to inject strongly typed configuration settings into your classes. It is a great way to keep your configuration settings in one place and to avoid having to use the IConfiguration
interface directly in your classes.
How to use it
mkdir IOptionsPatternDemo
cd IOptionsPatternDemo
Create a new ASP.NET Core Web Application
dotnet new webapi -o IOptionsPatternDemo
cd IOptionsPatternDemo
Step 1. Create a new class called JwtSettings
in the Models
folder
public class JwtSettings
{
public string Secret { get; set; } = string.Empty;
public string Issuer { get; set; } = string.Empty;
public string Audience { get; set; } = string.Empty;
public int ExpirationInMinutes { get; set; } = 0;
}
Step 2. Add the following to the appsettings.json file
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"JwtSettings": {
"Secret": "Damaam",
"Issuer": "me",
"Audience": "me",
"ExpirationInMinutes": 90
}
}
Step 3. Add the following to the Program.cs file
using OptionsPattern.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<JwtSettings>(builder.Configuration.GetSection("JwtSettings")); // <--- Add this line
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Create a new controller called UserController
in the Controllers
folder
[ApiController]
[Route("api/[controller]")]
public class UserControllers : ControllerBase
{
private readonly IOptions<JwtSettings> _jwtSettings;
public UserControllers(IOptions<JwtSettings> jwtSettings)
{
_jwtSettings = jwtSettings;
}
[HttpGet]
public IActionResult Get()
{
return Ok(_jwtSettings.Value);
}
//GET A SPECIFIC VALUE
[HttpGet("{key}")]
public IActionResult Get(string key)
{
var value = _jwtSettings.Value.GetType().GetProperty(key)?.GetValue(_jwtSettings.Value, null);
return Ok(value);
}
}
Run the application
dotnet run
💖 💪 🙅 🚩
Abayomi Ogunnusi
Posted on December 11, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.