I\'ve been looking through several examples of encrypting connectionStrings (Web.config) in an ASP.NET MVC application (.NET 4.0) and it seems that there are two general ways to
I've come up with a solution of my own, but I'm hoping that there is a better way to do it:
internal static class SecurityExtension
{
public static string GetConnetionString(this Configuration config, string databaseName, string provider = "RSAProtectedConfigurationProvider")
{
string sectionName = "connectionStrings";
ConfigurationSection section = config.GetSection(sectionName);
if (section != null && !section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection(provider);
config.Save();
}
return WebConfigurationManager.ConnectionStrings[databaseName].ConnectionString;
}
}
Now I just have to use the extension every time I want to get the configuration string:
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
string connectionString = config.GetConnetionString("MyDatabaseName");
Update:
Thanks to Brian, we can statically get the connection string:
private static HttpRequestWrapper request = new HttpRequestWrapper(System.Web.HttpContext.Current.Request);
private static Configuration config = WebConfigurationManager.OpenWebConfiguration(request.ApplicationPath);
private static string connectionString = config.GetConnetionString("MyDatabaseName"));
Of course you would not want to store the connection string like that, instead you would just use it to initialize your DataContext
or use it for whatever else you need.