问题描述
WebSecurity.Login
在 simplemembership 中使用用户名和密码,如何让它使用用户名或电子邮件而不是用户名登录用户?,让用户自由输入他的电子邮件或用户名登录.
WebSecurity.Login
in simplemembership take username and password, how to make it to login the user using username or email instead of just username?, to make the user free to enter his email or username to login.
推荐答案
您可以从 SimpleMembershipProvider
继承并像这样覆盖 ValidateUser
方法.
You could inherit from the SimpleMembershipProvider
and just override the ValidateUser
method like this.
public class ExtendedSimpleMembershipProvider : SimpleMembershipProvider
{
public override bool ValidateUser(string login, string password)
{
// check to see if the login passed is an email address
if (IsValidEmail(login))
{
string actualUsername = base.GetUserNameByEmail(login);
return base.ValidateUser(actualUsername, password);
}
else
{
return base.ValidateUser(login, password);
}
}
bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, @"^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$");
}
}
这只是一种方法.您可以编写自己的 MembershipProvider
但如果您只需要更改 ValidateUser
方法,这应该可以工作.
This is just one approach. You could write your own MembershipProvider
but if you only need to change the ValidateUser
method this should work.
将以下配置添加到 web.config 以设置提供程序.
Add the following configuration to the web.config to setup the provider.
<membership defaultProvider="ExtendedSimpleMembershipProvider">
<providers>
<clear/>
<add name="ExtendedSimpleMembershipProvider"
type="MyProject.Web.SimpleMembershipProvider, MyProject.Web"/>
</providers>
</membership>
这应该会让你朝着正确的方向前进.
That should get you going in the right direction.
这篇关于如何使 WebSecurity.Login 使用用户名或电子邮件登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!