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 Rajan
Abhith RajanSeptember 15, 2019 · 2 min read · Last Updated:

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


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;
4public static string ConnectionString
6 get { return ConfigurationManager.ConnectionStrings["Default"].ConnectionString; }

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

Abhith Rajan

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

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

Related SnippetsView All

Related ArticlesView All

Related VideosView All

What is Span in C# and why you should be using it

C# 10 - New Features in .NET 6

C# Channels Explained (System.Threading.Channels)

Related StoriesView All

Related Tools & ServicesView All

SmarterASP.NET - Unlimited ASP.NET Web Hosting

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