aspnet , c-sharp , web-config ,

C# - Get Web.Config Connection String in a Class Library

by Abhith Rajan FollowSeptember 15, 2019 · 1 min read · Last Updated:
Share this

This is relatively old topic but looks like still relevant. You need to know why?

Story

Recently one of our vendor deployed an app in one of our environment and when tested, found that the some of the entries going to wrong DB. Checked the connection strings in Web.Config, everything was fine. Due to the lack of proper logging in the application, we planned to hook up Microsoft Azure Application Insights, and we did discovered something, thanks to AI.

Hard coding something like Connection String is a BAD PRACTICE, things like that should come as a parameter to the class library methods. Since we are not in a position to rewrite everything, what we did was, we replaced the hard coded connection string with the actual connection string value from the web.config.

using  System.Configuration;
...

public static string ConnectionString
{
  get { return ConfigurationManager.ConnectionStrings["Default"].ConnectionString; }
}

In the above code, Default is the connection string name in the web.config.

This page is open source. Noticed a typo? Or something unclear?
Improve this page on GitHub

Abhith Rajan

Written by Abhith Rajan FollowBuy me a coffee
Abhith Rajan is an aspiring software engineer with more than 6 years of experience and proven successful track record of delivering technology-based products and services.

Related Services

SmarterASP.net - Unlimited ASP.NET Web Hosting

ASP.NET Hosting by SmarterASP.net. Unlimited ASP.NET Hosting Plans Starting at $2.95 a month.