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

commit 57434a8 · authored · 1 min read

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

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.

local graph · open full graph

"C# - Get Web.Config Connection String in a Class Library" is connected to the topics ASP.NET, C#, Web.config and related to 8 other entries. Redirect HTTPS requests to HTTP using IIS Rewrite rule in Web.Config Redirect HTTPS requests to … Redirect HTTP to HTTPS using Web.Config in IIS Redirect HTTP to HTTPS usin… Redirect WWW to Non-WWW using Web.Config in IIS Redirect WWW to Non-WWW usi… Check if string is Arabic - C# Check if string is Arabic -… Redirect non-www urls to www urls Redirect non-www urls to ww… NDepend - The Best-in-class Static Code Analyzer for Dotnet NDepend - The Best-in-class… Truncate String Without Word Break Truncate String Without Wor… Mask String Mask String ASP.NET #aspnet C# #c-sharp Web.config #web-config C# - Get Web.Config Connection St…

comments

loading discussion…