Friday, November 7, 2008

ASP .NET Connection Strings in Web.config File

ASP .NET offers an elegant way to store data source connection creditentials. Connection strings should be stored in a .config file, commonly and by default the Web.config file.

Firstly, what are connection strings? Connection strings are strings of text that contain information about a data source used in the code for data access. Information contained in a connection string includes the data source name, data source address, security mode, login creditentials, and the data source type.

There are a couple reasons why the Web.config file is a good place to store connection. One, ASP .NET is automatically configured to never display a file with a .config extension. So you can assume a level of security when storing login information in the Web.config. In addition, ASP .NET can be configured to encrypt the Web.config file, which would add more security. Nonetheless, you can be assured that any web request to a .config file would result in an error. Secondly, using Web.config allows a central way to manage information without requiring digging into the code nor code modification.

Below are examples of how connection strings would be used:

<?xml version="1.0"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
 <connectionStrings>
  <add name="connectionName" connectionString="Data Source=serverName;
  Initial Catalog=databaseName;User Id=username;Password=password;"
  providerName="System.Data.SqlClient"/>
</connectionStrings>
...
</configuration>



To retrieve the above connection string in C# code:

string connStr = ConfigurationManager.ConnectionStrings["connectionName"];



To use the connection string directly in an ASP .NET page:

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
  ConnectionString="<%$ ConnectionStrings:connectionName %>"
  SelectCommand="SELECT * FROM [Employees]" />