ASP.NET
web.config
connection string
application configuration
C# development

Read connection string 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

Reading a database connection string from web.config is standard in ASP.NET, but many failures happen because configuration keys drift between environments. The code to load the value is short, yet safe usage requires startup validation, secret hygiene, and clear fallback policy. A good implementation should fail fast when configuration is wrong instead of failing later during the first database call.

Core Sections

Define connection strings in the right section

In classic ASP.NET applications, keep database strings in the connectionStrings section of web.config. Do not place database credentials in custom app settings keys unless you have a clear reason.

xml
1<configuration>
2  <connectionStrings>
3    <add name="AppDb"
4         connectionString="Server=localhost;Database=appdb;Integrated Security=true;"
5         providerName="System.Data.SqlClient" />
6  </connectionStrings>
7</configuration>

Keeping the key name stable across all environments is more important than the exact value format. Most deployment bugs are naming mismatches, not parser issues.

Read values with ConfigurationManager

Use ConfigurationManager.ConnectionStrings and explicitly check for missing entries.

csharp
1using System;
2using System.Configuration;
3
4public static class DbConfig
5{
6    public static string GetConnectionString(string name)
7    {
8        ConnectionStringSettings cs = ConfigurationManager.ConnectionStrings[name];
9        if (cs == null || string.IsNullOrWhiteSpace(cs.ConnectionString))
10        {
11            throw new ConfigurationErrorsException($"Missing connection string: {name}");
12        }
13
14        return cs.ConnectionString;
15    }
16}

This pattern gives one clear error path and prevents null reference failures in unrelated layers.

Validate configuration at startup

Load and validate required connection strings during application startup. It is better to stop startup than to pass health checks and crash on first request.

csharp
1public class StartupValidator
2{
3    public static void Validate()
4    {
5        string appDb = DbConfig.GetConnectionString("AppDb");
6        if (!appDb.Contains("Database=", StringComparison.OrdinalIgnoreCase))
7        {
8            throw new ConfigurationErrorsException("AppDb must include Database value");
9        }
10    }
11}

If you have multiple data stores, validate all of them in one startup routine and log which key failed.

Handle environment-specific values safely

Different environments need different values, but key names should remain identical. Use transform files, environment variable injection, or deployment secrets to swap values. Do not edit production web.config manually unless it is part of a controlled emergency process.

For secret rotation, prefer mechanisms that update values without source control exposure. Even if configuration is encrypted at rest, limit who can read plaintext values in running environments.

Protect against accidental credential leakage

Connection strings often contain usernames and passwords. Never log full raw strings. If logging is required for debugging, log only key metadata such as server host and database name after masking.

A simple rule is to log connection key names and validation result, not connection values. This keeps observability useful without creating a new security risk.

Testing strategy for configuration reliability

Add a configuration unit test or integration check that verifies required keys exist in deployment templates. Also test that invalid configurations fail early with useful error messages.

For example, run a smoke check in CI that starts the app with test settings and confirms startup validation passes. Then run one negative test with missing AppDb to confirm failure mode remains clear after refactors.

Plan migration from legacy to modern secret sources

Many teams keep web.config for key names but move secret values to managed secret stores. This migration should keep public interfaces stable so application code still calls one configuration reader while the backing value source changes by environment. A staged migration with compatibility tests avoids outages during rollout.

Keep one fallback mechanism for emergency recovery, but document when it is allowed and how it is audited.

Common Pitfalls

  • Reading connection strings from appSettings instead of connectionStrings without a documented reason.
  • Using different key names across environments and relying on manual mapping.
  • Delaying validation until the first request hits the database.
  • Logging full connection strings that contain credentials.
  • Applying manual production edits outside a versioned deployment workflow.

Summary

  • Store database strings in connectionStrings with stable key names.
  • Read values through ConfigurationManager.ConnectionStrings with explicit null checks.
  • Validate required keys during startup to fail fast on bad config.
  • Separate environment values from source code and avoid secret leakage in logs.
  • Add automated checks so configuration errors are caught before deployment.

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.