Avoid magic strings in ASP.NET configuration

Getting data from configuration file, we can use something like this

appsettings.json

"ExternalApi": {
    "apiUrl": "localhost:5000",
    "apiClient": "client_123",
    "apiSecret":  "secret_123"
  }

And we can read the values using this code, notice the use of magic string.

[ApiController]
    public class TestController : Controller
    {
        private readonly IConfiguration _configuration;
        public TestController(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        [HttpGet("/test")]
        public IActionResult Index()
        {
            var apiUrl = _configuration["ExternalApi:apiUrl"];
            var apiClient = _configuration["ExternalApi:apiClient"];
            var apiSecret = _configuration["ExternalApi:apiSecret"];
            return Ok($"{apiUrl} {apiClient} {apiSecret}");
        }
    }

Magic strings are problematic because they can be difficult to maintain, error-prone, and can lead to issues such as typos, spelling mistakes, and inconsistency.

Instead we can create strong data type to represent the configuration

public class ExternalApiConfig
    {
        public string ApiUrl { get; set; }
        public string ApiClient { get; set; }
        public string ApiSecret { get; set; }
    }

and then register the type in Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
const string ExternalApi = "ExternalApi";
builder.Services.Configure<ExternalApiConfig>(builder.Configuration.GetSection(ExternalApi));

var app = builder.Build();

And then we can use it in any other class like this

[ApiController]
    public class TestController : Controller
    {
        private readonly ExternalApiConfig _externalApiConfig;
        public TestController(IOptions<ExternalApiConfig> externalApiConfig)
        {
            _externalApiConfig = externalApiConfig.Value;
        }

        [HttpGet("/test")]
        public IActionResult Index()
        {
            var apiUrl = _externalApiConfig.ApiUrl;
            var apiClient = _externalApiConfig.ApiClient;
            var apiSecret = _externalApiConfig.ApiSecret;

            return Ok($"{apiUrl}  {apiClient}  {apiSecret}");
        }
    }
Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s