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 · 1 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.

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 byAbhith Rajan
Abhith Rajan is a software engineer by day and a full-stack developer by night. He's coding for almost a decade now. He codes 🧑‍💻, write ✍️, learn 📖 and advocate 👍.
Connect

Is this page helpful?

Related SnippetsView All

Related ArticlesView All

Related VideosView All

C# Project Management in VS Code [Pt 3] | C# and .NET Development in VS Code for Beginners

Installing VS Code and C# Dev Kit [Pt 2] | C# and .NET Development in VS Code for Beginners

What is VS Code and C# Dev Kit? [Pt 1] | C# and .NET Development in VS Code for Beginners

Related Tools & ServicesView All

SmarterASP.NET

SmarterASP.net - Unlimited ASP.NET Web Hosting

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