0

有没有办法调用我在代码中实现的自定义 MembershipProvider 而不必每次都将 Membership 类转换为我的自定义提供程序?例如,我像这样设置我的 web.config:

<connectionStrings>
    <add name="TestDB"
         connectionString="conn_str_here"
         providerName="System.Data.SqlClient" />
</connectionStrings>

<membership defaultProvider="CustomSqlMembershipProvider">
    <providers>
    <clear/>
    <add name="CustomSqlMembershipProvider" type="Common.CustomSqlMembershipProvider" connectionStringName="TestDB"
         enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
         maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
         applicationName="/" />
    </providers>
</membership>

还有我的自定义提供者类:

namespace Common 
{
    public class CustomSqlMembershipProvider : SqlMembershipProvider
    {
        public void ChangeUsername()
        {
            // ...
        }
    }
}

现在调用我的新自定义函数,是否有一些方法可以允许Membership.ChangeUsername()而不是必须这样做:

CustomSqlMembershipProvider customMembership = Membership.Provider as CustomSqlMembershipProvider;
customMembership.ChangeUsername();

在任何你想使用它的地方做演员,一段时间后开始变得烦人。提前致谢。

4

1 回答 1

0

您可以添加一个扩展方法:

namespace System.Web.Membership
{
    public static class MembershipProviderExtensions
    {
        public static void ChangeUsername(this MembershipProvider provider, string oldUsername, string newUsername)
        {
            var customProvider = provider as CustomSqlMembershipProvider;
            if (customProvider == null) throw new Exception("Invalid provider type.");

            customProvider.ChangeUsername(oldUsername, newUsername);
        }
    }
}

用法:

Membership.Provider.ChangeUsername("bob", "jane");
于 2012-08-29T21:02:55.837 回答