web.config for ASP.NET developers: appSettings, connection strings and request validation
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
- Keys are case-insensitive when read, but a misspelled key returns
nullsilently. Centralise the names in one class, as above, so a typo appears in one place only. bool.TryParseaccepts "true"/"false" in any case, but not "1", "yes" or "on". Document the expected values next to the key.- Reading settings in a static field initialiser caches them for the life of the application domain; that is usually fine, since changing
web.configrestarts the domain anyway.
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
| connectionStrings | appSettings | |
|---|---|---|
| Purpose | Database connections | General settings |
| Extra attributes | providerName | None |
| Used by | Data source controls, Entity Framework, membership providers | Your code, some libraries |
| External file | configSource="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
- Prefer integrated security (the application pool identity) so no password is stored.
- Otherwise encrypt the section on the server:
aspnet_regiis -pef connectionStrings C:\inetpub\shop. ASP.NET decrypts it transparently at run time. - Keep production secrets out of source control by using
appSettings file="…"orconfigSourcewith a file that is not committed.
Step-by-step guides: get a connection string and connect to SQL Server and read appSettings values.
Common mistakes
- Reading a connection string through
AppSettings, or the reverse: each section has its own collection, so the key comes backnull. - Duplicate keys: in
appSettings, the last entry wins silently; inconnectionStrings, a duplicatenamecauses a configuration error unless you<remove>or<clear />inherited entries first. - Expecting a change in
web.configto be invisible: saving the file restarts the application.
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:
| Scenario | Example |
|---|---|
| SQL Server Express on the same machine | Data Source=.\SQLEXPRESS;Initial Catalog=Shop;Integrated Security=True |
| LocalDB (development) | Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Shop;Integrated Security=True |
| SQL Server login | Server=SQL01;Database=Shop;User ID=shop_web;Password=… |
| Azure SQL Database | Server=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
| Message | Likely 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 login | The 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 trusted | Encryption 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 use | Connections 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:
- If the field is plain text (a comment, a name containing "<3"), store it as is and encode on output:
<%#: Eval("Body") %>,Literal Mode="Encode",HttpUtility.HtmlEncode. The user's text is displayed, never executed. - If the field must contain formatting (a rich text editor), sanitise it with an allow-list HTML sanitiser library before storing or displaying, keeping only harmless tags (
p,b,awith safehref…) and removing scripts, event handler attributes andjavascript:URLs. Do not write your own sanitiser with regular expressions.
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
- Database connections live in
<connectionStrings>, everything else in<appSettings>, read once through a small typed helper. - Release values come from
Web.Release.configtransforms or the deployment pipeline, not from editing the file on the server. - Passwords are not committed: use integrated security, an external file kept out of source control, or an encrypted section.
- Request validation stays on; HTML input is allowed per control and then sanitised and encoded.
Sources
- Microsoft Learn: ConfigurationManager.AppSettings, <appSettings> element, Connection strings and configuration files, Encrypting configuration information using protected configuration, Connection string syntax, SQL Server connection pooling, Introduction to Microsoft.Data.SqlClient, Request validation: preventing script attacks, Control.ValidateRequestMode, HttpRequest.Unvalidated, requestValidationMode.
- OWASP: Cross Site Scripting Prevention Cheat Sheet.