简体   繁体   中英

Changing .net Membership ConnectionString

I need to change the connection string that the .net Membership API uses. Basically the API loads the connection string from app.config on the first time you are calling it.

Does anyone knows how can I dynamically tell the API to use a different connection string?

<system.web>
<membership defaultProvider="SqlProvider">
  <providers>
    <clear />
    <add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MySqlConnection"
         enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
         passwordFormat="Hashed" maxInvalidPasswordAttempts="6545"
         minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0"
         passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>
  </providers>
</membership>
<roleManager enabled="true" defaultProvider="RoleProvider">
  <providers>
    <add name="RoleProvider"
         type="System.Web.Security.SqlRoleProvider"
         connectionStringName="MySqlConnection" />
  </providers>
</roleManager>
</system.web>
<connectionStrings>
  <add name="MySqlConnection"
       connectionString=".." 
       providerName="System.Data.SqlClient" />
</connectionStrings> 

EDIT:

Solved - > Set connection string of membership dynamically from code

You need to create your own custom membership provider code (this is not as complicated as it sounds). You need to provide a class that inherits from SqlMembershipProvider, and then add an overriden initialise method:

public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
{
    // Get your new connnection string name and then overwrite the base here:
    config.Item["connectionStringName"] = "MyNewConnectionStringName";

    base.Initilize(name, config);
}

Then in your web.config, for the membership section, you need to put your new custom type in the 'type' attribute. This requires you to get your new connection string from the ConnectionStrings application section.

You may also need to also override the RoleProvider and the ProfileProvider depending on your requirements.

PS Code quickly translated on the fly from VB.net, apologies if there are a few syntax errors.


In the web.config, you must fully qualify your custom reference, something like (query from comments):

<add name="AspNetSqlMembershipProvider" 
type="zTester.tempMemebership, zTester, Version=1.0.0.0, Culture=neutral" ... etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM