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

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS