ASP.NET Database connection strings in web.config

The Connection string contains sensitive data like username, password, IP address of the server. When we place this sensitive data in an .aspx file for a web application or visual basic or C# files, we run the risk of exposing this data to a hacker.

So, we place this code in the web configuration file. Configuration files are used to store information about application settings.

These files are also referred to as Application Configuration Files and provide security to the data contained in them.

We place the connection string in App.config file for windows applications and web.config file for web applications.
-web.config is created automatically by VS.NET when you create any web project.

-When you compile the web application, web.config is NOT renamed or copied to the BIN folder.

-web.config has several default entries in it to support web/IIS configuration & security.

-You can add the <appSettings>section in the web.config and add your key/value pairs in that section.

-You can have separate web.config files for each directory in your web application, in addition to the one in the root. For each web page, by default, system will look for a web.config in the same folder as the page and if not found, then looks in the parent folder. The web.config file with the connection string will have the following content.

  < ?xml version="1.0"?>
  < configuration>
	< appSettings>
		< add key="DatabasePath"
		  value="server=localhost;
		database=FinAccounting;
		Integrated Security=true;"/>
	< /appSettings>
  < /configuration>

For the web.config file to be read, place the following code in your web application as shown below.

  Imports System.Configuration
  Imports System.Data.SqlClient

  Partial Class _Default
    Inherits System.Web.UI.Page

    Dim dbpath As String
	 = ConfigurationSettings.AppSettings("DatabasePath")
    Dim str_sql_user_select As String
	 = "SELECT * FROM AccountsTable"
    Dim comUserSelect As SqlCommand
    Dim myreader As SqlDataReader

    Protected Sub Page_Load
	(ByVal sender As Object, ByVal e As System.EventArgs)
	  Handles Me.Load

        Dim myConnection As SqlConnection
		 = New SqlConnection(dbpath)
        comUserSelect = New
		 SqlCommand(str_sql_user_select, myConnection)
        TextBox1.Text = ""
        TextBox2.Text = ""
        myConnection.Open()
        myreader = comUserSelect.ExecuteReader
        If (myreader.Read = True) Then
            TextBox1.Text = myreader(0)
            TextBox2.Text = myreader(1)
        Else
            MsgBox("You have reached eof")
        End If

    End Sub
  End Class

Leave a Reply