C# 我可以在运行时将 ConnectionStrings 添加到 ConnectionStringCollection 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/357465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I Add ConnectionStrings to the ConnectionStringCollection at Runtime?
提问by JamesEggers
Is there a way where I can add a connection string to the ConnectionStringCollection returned by the ConfigurationManager at runtime in an Asp.Net application?
有没有一种方法可以将连接字符串添加到由 ConfigurationManager 在运行时在 Asp.Net 应用程序中返回的 ConnectionStringCollection 中?
I have tried the following but am told that the configuration file is readonly.
我尝试了以下操作,但被告知配置文件是只读的。
ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings(params));
Is there another way to do this at runtime? I know at design time I can add a connection string to the web.config; however, I'm looking to add something to that collection at run time.
有没有另一种方法可以在运行时做到这一点?我知道在设计时我可以向 web.config 添加一个连接字符串;但是,我希望在运行时向该集合添加一些内容。
Thanks
谢谢
EDIT: One of the reasons why I'm attempting to do this is due to a security requirement that prevents me from placing ConnectionStrings in the web.config (even encrypted). I would like to use elements like Membership and Profiles on my project; however, I am looking into an alternative to doing such w/o writing a custom provider. Custom Provider's aren't all that bad, but if I can find an easier solution, I'm all for it.
编辑:我尝试这样做的原因之一是由于安全要求阻止我将 ConnectionStrings 放在 web.config (甚至加密)中。我想在我的项目中使用像 Membership 和 Profiles 这样的元素;但是,我正在寻找一种替代方法,可以在不编写自定义提供程序的情况下进行此类操作。自定义提供程序并不是那么糟糕,但如果我能找到一个更简单的解决方案,我完全赞成。
采纳答案by JoshBerke
var cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(@"/");
cfg.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(params));
cfg.Save();
Be Advised this will cause your website to recycle since it modifies the config file. Check out http://msdn.microsoft.com/en-us/library/4c2kcht0(VS.80).aspx
请注意,这将导致您的网站回收,因为它修改了配置文件。查看http://msdn.microsoft.com/en-us/library/4c2kcht0(VS.80).aspx
回答by ema
No, you can't modify the config file at runtime, it isn't intended for that. Maybe you could use the Enterprise Libraries Configuration to do that.
不,您不能在运行时修改配置文件,它不是为此而设计的。也许您可以使用企业库配置来做到这一点。
回答by joshperry
If you are trying to edit the connection strings in your web.config at runtime take a look at WebConfigurationManager.
如果您尝试在运行时编辑 web.config 中的连接字符串,请查看WebConfigurationManager。
If you are just trying to modify the configuration at runtime to inject a connection string then you are out of luck. The ConfigurationManager object tree is meant to be a direct reflection of the configuration files, if you were able to change that the state would then be inconsistent.
如果您只是想在运行时修改配置以注入连接字符串,那么您就不走运了。ConfigurationManager 对象树旨在直接反映配置文件,如果您能够更改状态,那么状态就会不一致。
I would recommend creating a simple facade class that you could use to retrieve your connection strings. This way you could have the facade return a connection string from your on the fly collection or if one doesn't exist then it could grab it from the ConfigurationManager.
我建议创建一个简单的外观类,您可以使用它来检索连接字符串。通过这种方式,您可以让 Facade 从您的动态集合中返回一个连接字符串,或者如果一个连接字符串不存在,那么它可以从 ConfigurationManager 中获取它。
class ConnectionStringProvider
{
Dictionary<string, System.Configuration.ConnectionStringSettings> _localStrings = new Dictionary<string, System.Configuration.ConnectionStringSettings>();
public void AddLocalConnectionString(string name, string connstring)
{
System.Configuration.ConnectionStringSettings cs = new System.Configuration.ConnectionStringSettings(name, connstring);
_localStrings.Add(name, cs);
}
public void RemoveLocalConnectionString(string name)
{
_localStrings.Remove(name);
}
public System.Configuration.ConnectionStringSettings this[string name] {
get
{
return _localStrings.ContainsKey(name) ? _localStrings[name] : System.Configuration.ConfigurationManager.ConnectionStrings[name];
}
}
}
Or you could always go quite a bit heavier and use something like the Enterprise Library Configuration Block.
或者你总是可以更重一些并使用诸如企业库配置块之类的东西。
回答by Scott Isaacs
Haven't tried it yet, but perhaps you can alter the value of an existing connection string at runtime? For example, instead of:
还没有尝试过,但也许您可以在运行时更改现有连接字符串的值?例如,而不是:
ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings(params));
Maybe you could do something like:
也许你可以这样做:
ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString = "something";
If so, you could specify the connection string "variables" in config, but set them to false or empty connection strings:
如果是这样,您可以在配置中指定连接字符串“变量”,但将它们设置为 false 或空连接字符串:
<add name="myconnection" connectionString="SET AT RUNTIME" ... />
回答by Chris Marisic
Just to point out whoever gave you the "security requirement" that you can't place the connection string in the web.config is an idiot. The web.config can never be accessed by anything other than your application or remote access to the server.
只是指出谁给了你“安全要求”,你不能把连接字符串放在 web.config 中是一个白痴。除了您的应用程序或对服务器的远程访问之外,任何东西都无法访问 web.config。
This sounds entirely like a requirements problem and should be solved there.
这听起来完全像是一个需求问题,应该在那里解决。
回答by joshperry
The configuration infrastructure supports very robust encryption through the Windows DataProtection API wich uses a machine specific key to encrypt the configuration sections. This way it would not be possible to read the encrypted data anywhere but on the machine where it was encrypted.
配置基础结构通过 Windows DataProtection API 支持非常强大的加密,它使用机器特定的密钥来加密配置部分。这样,除了在加密的机器上之外,不可能在任何地方读取加密数据。
This is the same API that is used for the Government compliant drive/folder encryption in Windows. Would this stand up to your companies security requirements?
这与 Windows 中用于政府兼容驱动器/文件夹加密的 API 相同。这能满足贵公司的安全要求吗?
Either manually or through your deployment automation you can execute this command to encrypt the connectionStrings section of your web.config for a specific web application.
无论是手动还是通过部署自动化,您都可以执行此命令来加密特定 Web 应用程序的 web.config 的 connectionStrings 部分。
aspnet_regiis -pe "connectionStrings" -app "/MyCoolWebApplication" -prov "DataProtectionConfigurationProvider"
回答by Kibbee
If you are using MS SQL you can configure you web server to access the SQL Server via the windows authentication, so you never have to have any passwords at all in your webconfig, or even floating around in your application memory.
如果您使用的是 MS SQL,您可以配置您的 Web 服务器以通过 Windows 身份验证访问 SQL Server,因此您的 webconfig 中根本不需要任何密码,甚至不需要在应用程序内存中浮动。
回答by user423430
You can use reflection to disable the private bReadOnly field (bad idea, etc.):
您可以使用反射来禁用私有 bReadOnly 字段(坏主意等):
typeof(ConfigurationElementCollection)
.GetField("bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic)
.SetValue(ConfigurationManager.ConnectionStrings, false);
ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings());
This is similar to the technique required to modify an existing connection string, and added as a comment there by Brian Rodgers.
这类似于修改现有连接字符串所需的技术,并由 Brian Rodgers 添加为注释。