ASP.NET: Connecting to MSSQL Server using Windows Authentication/Credentials

How To | May 12th, 2010

I am learning ASP and ASP.NET for my new job, and today I was working on manipulating a Microsoft SQL database (SCUD) when I ran into a roadblock. I knew I had to use my own user credentials to connect to the secret through ASP.NET, something I thought would be a very simple matter. Well after fifteen minutes of attempting to work out why I couldn’t connect with my username and password (trying variations of the domain/myusername) I finally discovered the MSDN page I needed. Yes, it already exists there, but the fact that it took me so long to find what  I needed means it can’t hurt to refer to it and reinforce it’s presence on the web.

The full MSDN article is here. I will summarize the multi-page verbose article with the two important points that you need to make the connection.

1. Modifying your web.config

Replace <connectionStrings /> with one of the following <add />’s:


<connectionStrings>
  <add name="MyDbConn1"
       connectionString="Server=MyServer;Database=MyDb;Trusted_Connection=Yes;"/>
  <add name="MyDbConn2"
      connectionString="Initial Catalog=MyDb;Data Source=MyServer;Integrated Security=SSPI;"/>
</connectionStrings>
</pre>

And obviously, change the MyServer to your server’s name (i.e. localhost or 172.0.0.1 or whatever address.), change MyDb to the name of the database you want to use in the server. Simple!

2. Open the connection in your ASP script

Use the following code wherever in your script.

At the top of your page, you need to make the include to the framework API:

<%@ Import Namespace="System.Data.SqlClient" %>

And then you’re free to use the following to connect when you need to. This is in C#.

string connStr = ConfigurationManager.ConnectionStrings["MyDbConn1"].ToString();
SqlConnection conn = new SqlConnection(connStr);

And walah! You should be connected.

More short articles will follow further explaining performing queries and outputting data.

  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Live
  • Ping.fm
  • Reddit
  • Slashdot
  • StumbleUpon
  • Technorati
  • Twitter
  • Yahoo! Bookmarks
  • Tumblr
  • RSS
  • Yahoo! Buzz
  • Design Float
  • DZone

Leave a Reply