aspnet | c-sharp | web-config

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

If you can, pass the connection string as a parameter to the class library. Second option is System.Configuration.ConfigurationManager

Abhith RajanSeptember 15, 2019 ยท 2 min read ยท Last Updated:

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.

1using System.Configuration;
2...
3
4public static string ConnectionString
5{
6 get { return ConfigurationManager.ConnectionStrings["Default"].ConnectionString; }
7}

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

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

Was this article helpful?

Your opinion matters

Please share your thought about this article

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

Related Posts

Related Stories

Related Tools & 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.