动态设置和修改Membership/Profile/RoleProvider的ConnectionString数据库连接字符串
时间:2011-04-14 来源:Mainz
一般使用Membership的人都知道,其ConnectionString数据库连接字符串是在web.config/app.config里面设置的,例如:
<membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="SqlServices" applicationName="MyApplication" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" minRequiredPasswordLength="3" minRequiredNonalphanumericCharacters="0" />
</providers>
</membership>
那么在程序中是否有可能根据不同的环境来动态指定MemberShip所用的数据库连接ConnectionString呢?
我想这个要求是很多人都会遇到的,其实很简单,几行代码就搞定了,也不需要扩展一个自定义的MembershipProvider,上代码:
/// <summary>
/// Sets the provider connection string.
/// </summary>
/// <param name="connectionString">The connection string.</param>
private void SetProviderConnectionString(string connectionString)
{
var connectionStringField = Membership.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
if (connectionStringField != null)
connectionStringField.SetValue(Membership.Provider, connectionString);
var roleField = Roles.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
if (roleField != null)
roleField.SetValue(Roles.Provider, connectionString);
var profileField = ProfileManager.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
if (profileField != null)
profileField.SetValue(ProfileManager.Provider, connectionString);
}
代码用法:
当你在运行时需要切换Membership的数据库连接ConnectionString的时候,调用一下这个函数就会刷新到新的数据库了。很简单。
参考文献:Setting Membership/Profile/Role provider's connection string at runtime
相关阅读 更多 +