Thursday, December 20, 2012

How to change ASP.NET membership database connection string dynamically?

By reflection:
        private void SetProviderConnectionString(string connectionString)
        {
            // Set private property of Membership, Role and Profile providers.
            FieldInfo connectionStringField = Membership.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic); 
            if (connectionStringField != null)
                connectionStringField.SetValue(Membership.Provider, connectionString);

            FieldInfo roleField = Roles.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
            if (roleField != null)
                roleField.SetValue(Roles.Provider, connectionString);

            FieldInfo profileField = ProfileManager.Provider.GetType().GetField("_sqlConnectionString", BindingFlags.Instance | BindingFlags.NonPublic);
            if (profileField != null) 
                profileField.SetValue(ProfileManager.Provider, connectionString);
        }

No comments:

Post a Comment