Nota: Este artigo foi publicado originalmente em 2011. While the concepts remain valid for .NET Framework applications, modern .NET (Core and later) applications use appsettings.json instead of web.config. Consulte a documentação atual de ASP.NET documentation for the latest practices.

One of the most common questions for developers new to ASP.NET is where to place the database connection string in the web.config file. This guide shows the exact placement, provides examples for various database providers, and covers best practices for managing connection strings securely.

Introdução

The web.config file is the primary configuration file for ASP.NET web applications running on the .NET Framework. It uses XML format and controls everything from authentication settings to database connections. The connectionStrings section is where you define named connection strings that your application code references to connect to databases and other data sources.

Correct Placement in web.config

The connectionStrings section belongs inside the root <configuration> element, at the same level as <system.web>. Here is the correct structure:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <!-- Connection strings go here, at the same level as system.web -->
  <connectionStrings>
    <add name="MyDatabase"
         connectionString="Server=myserver;Database=mydb;Trusted_Connection=True;"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

  <system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
  </system.web>

</configuration>

Important Rules

  • The <connectionStrings> section is a direct child of <configuration>.
  • It must not be placed inside <system.web>, <appSettings>, or any other section.
  • If a <configSections> element exists, it must come first, and <connectionStrings> should follow it.
  • The order of sibling sections within <configuration> does not strictly matter (except <configSections> which must be first), but convention places <connectionStrings> before <system.web>.

Complete web.config Example

Here is a more complete example showing where connectionStrings fits among other common sections:

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <configSections>
    <!-- Custom section declarations (must come first) -->
  </configSections>

  <connectionStrings>
    <clear />
    <add name="DefaultConnection"
         connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=MyAppDb;Integrated Security=True;MultipleActiveResultSets=True"
         providerName="System.Data.SqlClient" />
    <add name="ReportingDb"
         connectionString="Server=reportserver;Database=Reports;User Id=reportuser;Password=SecurePass123;"
         providerName="System.Data.SqlClient" />
  </connectionStrings>

  <appSettings>
    <add key="AppName" value="My Application" />
    <add key="MaxItemsPerPage" value="25" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.8" />
    <httpRuntime targetFramework="4.8" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
  </system.web>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>

</configuration>

Connection String Exemplos for Different Providers

SQL Server (Windows Authentication)

<add name="SqlServerTrusted"
     connectionString="Server=myserver;Database=mydb;Trusted_Connection=True;"
     providerName="System.Data.SqlClient" />

SQL Server (SQL Authentication)

<add name="SqlServerAuth"
     connectionString="Server=myserver;Database=mydb;User Id=myuser;Password=mypassword;"
     providerName="System.Data.SqlClient" />

SQL Server with Named Instance

<add name="SqlServerInstance"
     connectionString="Server=myserver\SQLEXPRESS;Database=mydb;Trusted_Connection=True;"
     providerName="System.Data.SqlClient" />

MySQL

<add name="MySqlConn"
     connectionString="Server=myserver;Database=mydb;Uid=myuser;Pwd=mypassword;Port=3306;"
     providerName="MySql.Data.MySqlClient" />

SQLite

<add name="SQLiteConn"
     connectionString="Data Source=|DataDirectory|\mydb.sqlite;Version=3;"
     providerName="System.Data.SQLite" />

Oracle

<add name="OracleConn"
     connectionString="Data Source=myserver:1521/myservice;User Id=myuser;Password=mypassword;"
     providerName="Oracle.ManagedDataAccess.Client" />

Accessing Connection Strings in Code

From C# Code

using System.Configuration;

// Read a connection string by name
string connString = ConfigurationManager
    .ConnectionStrings["DefaultConnection"]
    .ConnectionString;

// Use it with SqlConnection
using (var connection = new SqlConnection(connString))
{
    connection.Open();
    // Execute queries...
}

From Entity Framework (Database First)

Entity Framework typically adds its own connection string during model creation:

<add name="MyEntities"
     connectionString="metadata=res://*/Models.MyModel.csdl|
       res://*/Models.MyModel.ssdl|
       res://*/Models.MyModel.msl;
       provider=System.Data.SqlClient;
       provider connection string=&quot;
       Data Source=myserver;Initial Catalog=mydb;
       Integrated Security=True;
       MultipleActiveResultSets=True&quot;"
     providerName="System.Data.EntityClient" />

Using an External Configuração File

To keep connection strings separate from the main web.config (recommended for security):

web.config:

<connectionStrings configSource="connections.config" />

connections.config:

<connectionStrings>
  <add name="DefaultConnection"
       connectionString="Server=myserver;Database=mydb;Trusted_Connection=True;"
       providerName="System.Data.SqlClient" />
</connectionStrings>

Add connections.config to your .gitignore so credentials are not committed to source control.

Encrypting Connection Strings

To protect sensitive credentials in production, encrypt the connectionStrings section:

# Open the Visual Studio Developer Command Prompt and run:
aspnet_regiis -pe "connectionStrings" -app "/MyWebApp"

# To decrypt (for editing):
aspnet_regiis -pd "connectionStrings" -app "/MyWebApp"

After encryption, the connectionStrings section in web.config will contain encrypted cipher text, but ASP.NET will transparently decrypt it at runtime.

Solução de Problemas Connection String Issues

  1. “Format of the initialization string does not conform to specification” — Check for missing semicolons, unescaped special characters, or incorrect attribute names in the connection string.
  2. “Cannot open database requested by the login” — Verify the database name is correct and the user/service account has access to it.
  3. Connection string not found at runtime — Ensure the name attribute matches exactly what your code references (case-sensitive). Also verify the section is not nested inside another element.
  4. Entity Framework metadata errors — Make sure the metadata paths in EF connection strings match your model’s namespace and assembly.
  5. “Login failed for user” — When using SQL Authentication, double-check the username and password. When using Windows Authentication (Trusted_Connection=True), ensure the application pool identity has SQL Server access.

Resumo

The connectionStrings section in web.config belongs as a direct child of the <configuration> root element, at the same level as <system.web>. Use the <add> element with name, connectionString, and providerName attributes to define each connection. For production environments, always encrypt the section or use external configuration files to protect credentials. Modern .NET applications (Core and later) should use appsettings.json with the IConfiguração interface instead.

Artigos Relacionados