web.config
configuration
variable reading
asp.net
application settings

Read Variable from Web.Config

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In ASP.NET applications, the web.config file is the central place to store configuration values like database connection strings, API keys, and feature flags. Reading these values correctly matters because hardcoding settings into your source code makes deployments painful -- you would need to recompile every time a database server changes or an API key rotates. The web.config approach lets you change behavior without touching a single line of code.

Understanding Web.Config Structure

A web.config file is an XML document with several predefined sections. The two you will use most often are appSettings for simple key-value pairs and connectionStrings for database connections.

xml
1<?xml version="1.0" encoding="utf-8"?>
2<configuration>
3  <appSettings>
4    <add key="SiteName" value="My Application" />
5    <add key="MaxUploadSize" value="10485760" />
6    <add key="EnableLogging" value="true" />
7  </appSettings>
8
9  <connectionStrings>
10    <add name="DefaultConnection"
11         connectionString="Server=db.example.com;Database=AppDb;User Id=app;Password=secret;"
12         providerName="System.Data.SqlClient" />
13  </connectionStrings>
14</configuration>

Each appSettings entry is a key-value pair accessed by its key attribute. Connection strings are accessed by their name attribute and carry additional metadata like the database provider.

Reading AppSettings Values

The ConfigurationManager class in the System.Configuration namespace is the standard way to read from appSettings. The reason this class exists as a dedicated API (rather than parsing XML yourself) is that the framework handles caching, type safety, and environment-specific overrides for you.

csharp
1using System.Configuration;
2
3// Read a simple string value
4string siteName = ConfigurationManager.AppSettings["SiteName"];
5// Returns "My Application"
6
7// Values are always strings, so cast as needed
8int maxUpload = int.Parse(ConfigurationManager.AppSettings["MaxUploadSize"]);
9bool logging = bool.Parse(ConfigurationManager.AppSettings["EnableLogging"]);

If the key does not exist, AppSettings["MissingKey"] returns null rather than throwing an exception. Always check for null before parsing to avoid runtime crashes.

csharp
1string value = ConfigurationManager.AppSettings["MissingKey"];
2if (value == null)
3{
4    throw new ConfigurationErrorsException(
5        "Required setting 'MissingKey' not found in web.config");
6}

Reading Connection Strings

Connection strings have their own dedicated section because they carry more structure than a simple key-value pair. The ConnectionStrings property returns a ConnectionStringSettings object that includes both the connection string itself and the provider name.

csharp
1using System.Configuration;
2
3// Read connection string by name
4var connSettings = ConfigurationManager.ConnectionStrings["DefaultConnection"];
5
6string connectionString = connSettings.ConnectionString;
7// "Server=db.example.com;Database=AppDb;User Id=app;Password=secret;"
8
9string provider = connSettings.ProviderName;
10// "System.Data.SqlClient"

This separation of connection string from provider name lets you switch between SQL Server, MySQL, and PostgreSQL by changing the config file alone.

Custom Configuration Sections

For more complex settings that do not fit neatly into key-value pairs, you can define custom configuration sections. This involves creating a class that inherits from ConfigurationSection.

xml
1<configuration>
2  <configSections>
3    <section name="emailSettings"
4             type="MyApp.EmailConfigSection, MyApp" />
5  </configSections>
6
7  <emailSettings
8    smtpServer="smtp.example.com"
9    port="587"
10    useSsl="true"
11    fromAddress="[email protected]" />
12</configuration>
csharp
1using System.Configuration;
2
3public class EmailConfigSection : ConfigurationSection
4{
5    [ConfigurationProperty("smtpServer", IsRequired = true)]
6    public string SmtpServer => (string)this["smtpServer"];
7
8    [ConfigurationProperty("port", DefaultValue = 25)]
9    public int Port => (int)this["port"];
10
11    [ConfigurationProperty("useSsl", DefaultValue = false)]
12    public bool UseSsl => (bool)this["useSsl"];
13
14    [ConfigurationProperty("fromAddress", IsRequired = true)]
15    public string FromAddress => (string)this["fromAddress"];
16}
17
18// Usage
19var emailConfig = (EmailConfigSection)ConfigurationManager
20    .GetSection("emailSettings");
21string server = emailConfig.SmtpServer;  // "smtp.example.com"

Reading Configuration in ASP.NET Core

ASP.NET Core replaces web.config and ConfigurationManager with a new configuration system built on appsettings.json and the IConfiguration interface. If you are working with ASP.NET Core, this is the approach you should use instead.

json
1{
2  "SiteName": "My Application",
3  "ConnectionStrings": {
4    "DefaultConnection": "Server=db.example.com;Database=AppDb;"
5  },
6  "EmailSettings": {
7    "SmtpServer": "smtp.example.com",
8    "Port": 587
9  }
10}
csharp
1// In a controller or service (injected via DI)
2public class HomeController : Controller
3{
4    private readonly IConfiguration _config;
5
6    public HomeController(IConfiguration configuration)
7    {
8        _config = configuration;
9    }
10
11    public IActionResult Index()
12    {
13        string siteName = _config["SiteName"];
14        string connString = _config.GetConnectionString("DefaultConnection");
15        int port = _config.GetValue<int>("EmailSettings:Port");
16
17        return View();
18    }
19}

The IConfiguration system supports multiple sources (JSON files, environment variables, command-line arguments) and merges them with a clear precedence order. Environment variables override file values, which is essential for containerized deployments.

You can also bind entire sections to strongly typed classes:

csharp
1public class EmailSettings
2{
3    public string SmtpServer { get; set; }
4    public int Port { get; set; }
5}
6
7// In Startup.cs or Program.cs
8builder.Services.Configure<EmailSettings>(
9    builder.Configuration.GetSection("EmailSettings"));

Common Pitfalls

  • Missing the System.Configuration reference: In .NET Framework projects, you must add a reference to System.Configuration.dll. The using statement alone is not enough -- the project will compile but ConfigurationManager will not resolve.
  • Assuming AppSettings returns a typed value: All AppSettings values are strings. Forgetting to parse them to int, bool, or other types causes subtle bugs when you compare or calculate with the raw string.
  • Not handling missing keys: AppSettings["NonExistent"] returns null silently. Without a null check, the error only surfaces later as a NullReferenceException far from the actual problem.
  • Confusing .NET Framework and .NET Core configuration: ConfigurationManager does not exist in ASP.NET Core by default. Trying to use it in a Core project without the compatibility NuGet package leads to confusing compile errors.
  • Storing secrets in web.config committed to source control: Connection strings and API keys in web.config end up in your Git history. Use user secrets (development) or environment variables (production) for sensitive values.

Summary

  • Use ConfigurationManager.AppSettings["key"] to read simple key-value settings from the appSettings section of web.config.
  • Use ConfigurationManager.ConnectionStrings["name"] for database connection strings, which include both the connection string and provider name.
  • All AppSettings values are strings -- always parse them to the correct type and check for null on missing keys.
  • Custom configuration sections let you organize complex settings into strongly typed classes.
  • In ASP.NET Core, replace web.config with appsettings.json and inject IConfiguration through dependency injection.
  • Never store secrets directly in configuration files that are committed to source control.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.