Membership users generally know that the connectionstring database connection string is set in Web. config/APP. config, for example:
< 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 >
InProgramIs it possible to dynamically specify the database connection connectionstring used by membership according to different environments?
I think this requirement is something that many people will encounter. It's actually very simple, just a few lines.CodeThis is done, and you do not need to extend a custom membershipprovider. The Code is as follows:
/// <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 );
}
Code usage:
When you need to switch the membership database connection connectionstring during running, call this function to refresh it to the new database. Very simple.
References: Setting membership/profile/role provider's connection string at runtime