Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
YouTube Security VideosAndroid Police: Samsung is smashing records! #shorts #tech #phones(21.09.2026 um 13:55 Uhr)
YouTube Security Videosheise & c't: Bundesnetzagentur wollte diesen Futterautomaten verbieten(21.09.2026 um 13:53 Uhr)
YouTube Security VideosNeil Patel: Your Google Traffic Isn't An Asset It's A Loan #shorts(21.09.2026 um 14:05 Uhr)
Windows Tipps & SecurityF-14 A Tomcat Top Gun endlich als Revell Klemmbausteinmodell erhältlich(21.09.2026 um 14:27 Uhr)
Sichere ProgrammierungShow the Hand-Back Sample Before Approving an Agent Score(21.09.2026 um 14:15 Uhr)
Sichere ProgrammierungHybrid retrieval in one Postgres query: RRF over tsvector + pgvector(21.09.2026 um 14:15 Uhr)
YouTube Security VideosAndroid Police: Samsung is smashing records! #shorts #tech #phones(21.09.2026 um 13:55 Uhr)
YouTube Security Videosheise & c't: Bundesnetzagentur wollte diesen Futterautomaten verbieten(21.09.2026 um 13:53 Uhr)
YouTube Security VideosNeil Patel: Your Google Traffic Isn't An Asset It's A Loan #shorts(21.09.2026 um 14:05 Uhr)
Windows Tipps & SecurityF-14 A Tomcat Top Gun endlich als Revell Klemmbausteinmodell erhältlich(21.09.2026 um 14:27 Uhr)
Sichere ProgrammierungShow the Hand-Back Sample Before Approving an Agent Score(21.09.2026 um 14:15 Uhr)
Sichere ProgrammierungHybrid retrieval in one Postgres query: RRF over tsvector + pgvector(21.09.2026 um 14:15 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

How to C#: Add Configuration to your .NET 8 Web API Application

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…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

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

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten How to C#: Add Configuration to your .NET 8 Web API Application

Thematisch verwandte Begriffe: Configuration, your, Application · 6 Treffer

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-94097 | A vulnerability was determined in Netcore NBR200V2 1.3.241127.071246. Th…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick