Slider

AppSettings and IConfiguration

What is appsettings.json?

appsettings.json is a configuration file used in ASP.NET Core to store key-value pairs like:

  • Database connection strings
  • API keys
  • Feature toggles
  • Logging levels
  • Custom settings

Example:

{  "AppSettings": {
    "AppName": "MyApp",
    "Version": "1.0"
  },
  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=MyDb;Trusted_Connection=True;"
  }
}

What is IConfiguration?

IConfiguration is an interface provided by ASP.NET Core to access configuration data (like from appsettings.json, environment variables, etc.).
You can inject it into any class:

Example:
public class HomeController : Controller
{
    private readonly IConfiguration _config;

    public HomeController(IConfiguration config)
    {
        _config = config;
    }

    public IActionResult Index()
    {
        var appName = _config["AppSettings:AppName"];
        return Content($"App Name: {appName}");
    }
}

How to Bind Settings to a Class

You can also bind sections from appsettings.json to a class:

Step 1: Create a Class.
public class AppSettings
{
    public string AppName { get; set; }
    public string Version { get; set; }
}

Step 2: Register it in Program.cs
builder.Services.Configure<AppSettings>(
    builder.Configuration.GetSection("AppSettings"));

Step 3: Inject using IOptions<T>
public class HomeController : Controller
{
    private readonly AppSettings _settings;

    public HomeController(IOptions<AppSettings> options)
    {
        _settings = options.Value;
    }

    public IActionResult Index()
    {
        return Content($"App: {_settings.AppName}, Version: {_settings.Version}");
    }
}
ss
0

No comments

Post a Comment

both, mystorymag

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson
Table of Contents