Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp .Net Custom membership parameters from web.config

I am currently writting a custom membership provider for asp .net and the problem that I am having is that I don't know how to give parameters to the custom membership provider in the same way that you give to the standard asp .net membership providers in the web.config file like password length.

like image 203
Alecu Avatar asked Dec 21 '12 09:12

Alecu


1 Answers

When you derive your own class from MembershipProvider you have to override the Initialize() method, it has following signature:

public override void Initialize(string name, NameValueCollection config);

The System.Collections.NameValueCollection is a dictionary where you find the options written in the web.config file. These options are given in the same way you specify options for "standard" providers (as attributes). Each dictionary entry has the key of the attribute name and as value the attribute's value (as string).

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

        _enablePasswordReset = config.GetBoolean("enablePasswordReset", true);
    }
}

Where, in my example, GetBoolean() is an extension method declared somewhere as follow:

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;
    }
}
like image 93
Adriano Repetti Avatar answered Sep 20 '22 12:09

Adriano Repetti