来自web.config的Asp .Net Custom成员参数

Ale*_*ecu 6 asp.net asp.net-membership

我目前正在为asp .net写一个自定义成员资格提供程序,而我遇到的问题是我不知道如何以与提供给标准asp .net成员资格提供者相同的方式向自定义成员资格提供者提供参数在web.config文件中,如密码长度.

Adr*_*tti 5

从您派生自己的类时,MembershipProvider必须覆盖该Initialize()方法,它具有以下签名:

public override void Initialize(string name, NameValueCollection config);
Run Code Online (Sandbox Code Playgroud)

System.Collections.NameValueCollection是一个字典,您可以在其中找到web.config文件中写入的选项.这些选项的指定方式与指定"标准"提供程序的选项(作为属性)的方式相同.每个字典条目都具有属性名称的键,并且具有属性值(as string)的值.

public  class MyMembershipProvider : MembershipProvider
{
    public override void Initialize(string name, NameValueCollection config)
    {
        base.Initialize(name, config);

        _enablePasswordReset = config.GetBoolean("enablePasswordReset", true);
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的例子中,GetBoolean()在某处声明的扩展方法如下:

public static bool GetBoolean(this NameValueCollection config,
    string valueName, bool? defaultValue)
{
    object obj = config[valueName];
    if (obj == null)
    {
        if (!defaultValue.HasValue)
            throw new WarningException("Required field has not been specified.");

        return defaultValue.Value;
    }

    bool value = defaultValue;
    if (obj is Boolean)
        return (bool)obj;

    IConvertible convertible = obj as IConvertible;
    try
    {
        return convertible.ToBoolean(CultureInfo.InvariantCulture);
    }
    catch (Exception)
    {
        if (!defaultValue.HasValue)
            throw new WarningException("Required field has invalid format.");

        return defaultValue.Value;
    }
}
Run Code Online (Sandbox Code Playgroud)