以编程方式添加成员资格提供程

Sha*_*sek 3 .net membership-provider

我有一个使用任意数量的成员资格提供者的.Net应用程序.我不会理解这些原因,但我不希望这些原因得到预先配置,但我想以编程方式创建和添加它们.反正有没有这样做?我没有创建提供程序的问题,但Membership.Providers是readonly,所以我无法添加它们.

Dou*_*oug 6

迟到,迟到的答案,但你可以使用反射:

public static class ProviderUtil
{
    static private FieldInfo providerCollectionReadOnlyField;

    static ProviderUtil()
    {
        Type t = typeof(ProviderCollection);
        providerCollectionReadOnlyField = t.GetField("_ReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
    }

    static public void AddTo(this ProviderBase provider, ProviderCollection pc)
    {
        bool prevValue = (bool)providerCollectionReadOnlyField.GetValue(pc);
        if (prevValue)
            providerCollectionReadOnlyField.SetValue(pc, false);

        pc.Add(provider);

        if (prevValue)
            providerCollectionReadOnlyField.SetValue(pc, true);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,在您的代码中,您可以执行以下操作:

MyMembershipProvider provider = new MyMembershipProvider();
NameValueCollection config = new NameValueCollection();
// Configure your provider here.  For example,
config["username"] = "myUsername";
config["password"] = "myPassword";
provider.Initialize("MyProvider", config); 

// Add your provider to the membership provider list
provider.AddTo(Membership.Providers);
Run Code Online (Sandbox Code Playgroud)

这是一个黑客,因为我们使用反射设置"_ReadOnly"私有字段,但它似乎工作.

这是关于这个问题的一篇很棒的帖子:http: //elegantcode.com/2008/04/17/testing-a-membership-provider/

另一个好帖子:http: //www.endswithsaurus.com/2010/03/inserting-membershipprovider-into.html

请特别注意在这些帖子中使用_ReadOnly的警告,因为您需要权衡操作只读集合的​​缺点与项目要求以及您要完成的任务.

问候,

-Doug