有没有办法调用我在代码中实现的自定义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();
在你想要使用它的任何地方进行演员会在一段时间后开始变得烦人。提前谢谢。
答案 0 :(得分: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");