問題描述
從 Web.Config 獲取 MembershipProvider 的屬性 (Get MembershipProvider's Properties from Web.Config)
I derived a class from MembershipProvider
in System.Web.Security
with the following definition:
public class RedditMembershipProvider : MembershipProvider
{
public RedditMembershipProvider()
{
}
public override int PasswordAttemptWindow
{
get { return 10; }
}
/* snip all the similar properties definition
*/
}
The issue is I want when the RedditMembershipProvider
is instantiated, I want all the properties to be read from the web.config, not from the code definition above:
<membership defaultProvider="RedditMembershipProvider">
<providers>
<clear/>
<add name="RedditMembershipProvider"
type="RedditClone.Models.RedditMembershipProvider"
PasswordAttemptWindow=20
/>
</providers>
</membership>
So when I call the PasswordAttemptWindow
from the View, I should get 20, not 10. But now I am getting 10, not 20.
Any idea how to solve this problem?
參考解法
方法 1:
public class YourMembershipProvider : MembershipProvider
{
public override void Initialize(string name, NameValueCollection config)
{
if (!String.IsNullOrEmpty(config["yourValue"]))
{
_yourValue = config["yourValue"];
}
base.Initialize(name, config);
}
string _yourValue;
public override string YourValue
{
get
{
return _yourValue;
}
}
...
}
Edit: typo.
方法 2:
Silly me! How can I make this kind of mistake?
I just need to read web.config in my code to get the value out
public override int PasswordAttemptWindow
{
get { ConfigurationManager.AppSettings["membership"].value; }
}
An even easier way is to inherit the RedditMembershipProvider
from SqlMembershipProvider
and override only necessary details.
方法 3:
The answer 1 is elegant way. For example to read property minRequiredPasswordLength
use
public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config) {
if (!String.IsNullOrEmpty(config["minRequiredPasswordLength"])) {
_minRequiredPasswordLength = Int32.Parse(config["minRequiredPasswordLength"]);
}
base.Initialize(name, config);
}
and then
public override int MinRequiredPasswordLength {
get { return _minRequiredPasswordLength; }
}
(by Graviton、eu-ge-ne、Graviton、rosta)