ASP.NET

web.config for ASP.NET developers: appSettings, connection strings and request validation

ASP.NET · · Published 2026-11-29

web.config is where an ASP.NET application keeps what should not be compiled into it: settings that change between test and production, database connections, security switches. Most developers only ever touch four parts of it: <appSettings>, <connectionStrings>, the code that reads them, and the request-validation setting that produces the famous "potentially dangerous" error. This guide covers those four in order, from storing a value to reading it safely and protecting it.

The file at a glance

<configuration>
  <appSettings>
    <add key="PageSize" value="25" />
    <add key="SupportEmail" value="support@example.com" />
  </appSettings>
  <connectionStrings>
    <add name="Shop" providerName="System.Data.SqlClient"
         connectionString="Server=.;Database=Shop;Integrated Security=True" />
  </connectionStrings>
  <system.web>
    <compilation targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" requestValidationMode="4.5" />
  </system.web>
</configuration>

Each section below explains one of these blocks. If you only need a correct connection string, our connection string builder writes the <add> element for you.

Reading appSettings with typed defaults

The simplest section first: key-value strings that the code turns into typed settings.

The <appSettings> section holds simple key-value settings: a page size, a feature switch, an e-mail address. Reading them is one line; turning the strings into typed values with sensible defaults is where a small helper pays off.

The settings

<configuration>
  <appSettings>
    <add key="PageSize" value="25" />
    <add key="EnableNewCheckout" value="true" />
    <add key="AdminEmails" value="ops@example.org;billing@example.org" />
    <add key="SupportPhone" value="" />
  </appSettings>
</configuration>

Reading them

using System.Configuration;   // add a reference to System.Configuration

string raw = ConfigurationManager.AppSettings["PageSize"];   // "25", or null if the key is missing

A typed wrapper keeps conversions and defaults in one place:

public static class AppConfig
{
    public static int PageSize => GetInt("PageSize", 20, min: 5, max: 200);
    public static bool EnableNewCheckout => GetBool("EnableNewCheckout", false);
    public static string[] AdminEmails =>
        (ConfigurationManager.AppSettings["AdminEmails"] ?? "")
        .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
        .Select(s => s.Trim()).ToArray();

    private static int GetInt(string key, int fallback, int min, int max) =>
        int.TryParse(ConfigurationManager.AppSettings[key], NumberStyles.Integer, CultureInfo.InvariantCulture, out int v)
            && v >= min && v <= max ? v : fallback;

    private static bool GetBool(string key, bool fallback) =>
        bool.TryParse(ConfigurationManager.AppSettings[key], out bool v) ? v : fallback;
}

// usage
gvOrders.PageSize = AppConfig.PageSize;
if (AppConfig.EnableNewCheckout) { /* ... */ }

Parse numbers with the invariant culture so that a server set to a culture with different formats reads the file the same way.

In markup

<asp:Literal runat="server" Mode="Encode" Text="<%$ AppSettings:SupportPhone %>" />

The <%$ … %> expression builder only works in server control property values, not as free text in the page.

Changing a value on a live site

Saving web.config restarts the application domain: in-process session state is lost and the first request after the change is slower. Plan changes accordingly, or move frequently changed settings to a database table.

Secrets

An API key in appSettings ends up in source control unless you prevent it. Use the file attribute to merge values from a file that is not committed:

<appSettings file="App_Data\secrets.config">
  <add key="PageSize" value="25" />
</appSettings>
<!-- App_Data\secrets.config (not in source control) -->
<appSettings>
  <add key="PaymentApiKey" value="..." />
</appSettings>

If the external file is missing, ASP.NET simply ignores it, so the application still starts in development. The section can also be encrypted with aspnet_regiis, as explained in appSettings vs connectionStrings.

Common mistakes

appSettings or connectionStrings?

Both sections hold key-value pairs, so where does a database connection go, and why does it matter?

Both sections store key-value settings outside the code, and both can be changed without recompiling. connectionStrings is the dedicated place for database connections, with a provider name and a typed API; appSettings is for everything else.

<configuration>
  <connectionStrings>
    <add name="Db" providerName="System.Data.SqlClient"
         connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Shop;Integrated Security=True" />
  </connectionStrings>
  <appSettings>
    <add key="PageSize" value="20" />
    <add key="SupportEmail" value="support@example.org" />
  </appSettings>
</configuration>

Reading them

using System.Configuration; // reference System.Configuration.dll

ConnectionStringSettings db = ConfigurationManager.ConnectionStrings["Db"];
string cs = db.ConnectionString;
string provider = db.ProviderName;

string supportEmail = ConfigurationManager.AppSettings["SupportEmail"];   // null if missing
int pageSize = int.TryParse(ConfigurationManager.AppSettings["PageSize"], out int n) ? n : 20;

Values are strings; convert and validate them. Reading a missing connection string returns null, so ConfigurationManager.ConnectionStrings["Db"].ConnectionString throws a NullReferenceException if the name is misspelled.

In markup, expressions read them too: ConnectionString="<%$ ConnectionStrings:Db %>" on a SqlDataSource, Text="<%$ AppSettings:SupportEmail %>" on a label.

Differences that matter

connectionStringsappSettings
PurposeDatabase connectionsGeneral settings
Extra attributesproviderNameNone
Used byData source controls, Entity Framework, membership providersYour code, some libraries
External fileconfigSource="connections.config" (replaces the section)file="secrets.config" (merges, and the file may be missing)

Different values per environment

Web Config Transforms change values at publish time, for example in Web.Release.config:

<connectionStrings>
  <add name="Db" connectionString="Server=sql01;Database=Shop;Integrated Security=True"
       xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</connectionStrings>

Protecting secrets

Step-by-step guides: get a connection string and connect to SQL Server and read appSettings values.

Common mistakes

ASP.NET Core equivalent

ASP.NET Core replaces web.config sections with appsettings.json, environment variables and other configuration providers. Connection strings live under a "ConnectionStrings" object and are read with configuration.GetConnectionString("Db"); other settings are usually bound to typed options classes. Secrets belong in the Secret Manager during development and in environment variables or a vault in production.

From the connection string to an open SqlConnection

With the connection string in the right section, the code that uses it should follow one pattern everywhere.

Every data-driven Web Forms page starts the same way: read the connection string from web.config, open a SqlConnection, run a command, close it. Doing these steps correctly once, in a helper, saves a lot of trouble later.

1. Store it in web.config

<configuration>
  <connectionStrings>
    <!-- Windows authentication: the IIS application pool identity logs in -->
    <add name="Db" providerName="System.Data.SqlClient"
         connectionString="Data Source=SQL01;Initial Catalog=Shop;Integrated Security=True;Application Name=ShopWeb" />
  </connectionStrings>
</configuration>

Common variants of the connectionString value:

ScenarioExample
SQL Server Express on the same machineData Source=.\SQLEXPRESS;Initial Catalog=Shop;Integrated Security=True
LocalDB (development)Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Shop;Integrated Security=True
SQL Server loginServer=SQL01;Database=Shop;User ID=shop_web;Password=…
Azure SQL DatabaseServer=tcp:myserver.database.windows.net,1433;Database=Shop;User ID=…;Password=…;Encrypt=True

With Windows authentication, grant the application pool's identity (for example IIS APPPOOL\Shop) a login and only the database permissions it needs. With a SQL login, protect the password: see appSettings vs connectionStrings for encrypting the section.

2. Read it once

using System.Configuration;

public static class Db
{
    public static string ConnectionString { get; } =
        ConfigurationManager.ConnectionStrings["Db"]?.ConnectionString
        ?? throw new ConfigurationErrorsException("Connection string 'Db' is missing from web.config.");
}

Failing early with a clear message beats a NullReferenceException deep in a page.

3. Open, use, dispose

using (var con = new SqlConnection(Db.ConnectionString))
using (var cmd = new SqlCommand("SELECT COUNT(*) FROM dbo.Products", con))
{
    con.Open();
    int count = (int)cmd.ExecuteScalar();
    lblCount.Text = count.ToString();
}

Open late, close early: using returns the connection to the pool even if an exception is thrown. Creating a new SqlConnection per operation is cheap thanks to connection pooling; keeping one open in a static field or in session is a classic source of errors under load.

To write a new string or check an existing one against the documented keywords, use our connection string builder and checker.

Errors you may see

MessageLikely cause
A network-related or instance-specific error occurred… (error 26 or 40)Wrong server or instance name, SQL Browser stopped, TCP/IP disabled, or a firewall in between.
Login failed for user 'IIS APPPOOL\Shop'The pool identity has no login or no access to the database.
Cannot open database "Shop" requested by the loginThe login exists but has no user in that database, or the name is wrong.
The certificate chain was issued by an authority that is not trustedEncryption is on and the server's certificate is not trusted (common with Microsoft.Data.SqlClient 4+, where Encrypt defaults to true). Install a trusted certificate; use TrustServerCertificate=True only for development.
Timeout expired… all pooled connections were in useConnections are not being closed. Look for missing using blocks.

Next steps: running commands and keeping them safe with parameters.

Request validation and the "potentially dangerous" error

The last setting most developers meet is the one that rejects input looking like HTML.

A user types <b>bold</b> or <3 into a text box, clicks Save, and gets a yellow error page: "A potentially dangerous Request.Form value was detected from the client". This is request validation, a safety net that blocks input looking like HTML markup. The right response is to allow such input only where you need it, and to handle it safely.

What triggers it

Request validation inspects form fields, query strings and cookies for patterns such as < followed by a letter, !, / or ?, and &#. Ordinary text with a lone < followed by a space or digit passes; <script>, <b> and <!-- do not. The exception is HttpRequestValidationException.

Allow HTML for one control (.NET 4.5+)

<!-- web.config: keep the modern validation mode -->
<system.web>
  <httpRuntime targetFramework="4.8" requestValidationMode="4.5" />
</system.web>
<asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine" ValidateRequestMode="Disabled" />

With validation mode 4.5, values are validated lazily, when your code reads them, and ValidateRequestMode="Disabled" exempts just this control. Everything else on the page stays protected. In code, Request.Unvalidated.Form["field"] reads a raw value without triggering validation.

Avoid the old blanket fixes: ValidateRequest="false" on the whole page and requestValidationMode="2.0" in web.config, which weakens every page of the application.

Then make the HTML safe

Request validation was protecting you from storing and displaying script. Once you accept markup, that job is yours:

protected void btnSave_Click(object sender, EventArgs e)
{
    string raw = txtBody.Text;                    // allowed through for this control only
    string safe = HtmlSanitizerService.Clean(raw); // e.g. a maintained allow-list sanitiser library
    CommentRepository.Save(safe);
}

Showing a friendly message instead of the error page

// Global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
    if (Server.GetLastError() is HttpRequestValidationException)
    {
        Server.ClearError();
        Response.Redirect("~/Errors/InvalidInput.aspx", false);
        Context.ApplicationInstance.CompleteRequest();
    }
}

ASP.NET Core

ASP.NET Core has no request validation. Razor encodes output by default, which is the primary defence; sanitising rich text is still your responsibility.

Other errors met when moving an application: Parser Error when deploying.

Checklist

Sources