我正在关注Scott Millet撰写的Professional ASP.NET Design Patterns中的案例研究。在案例研究中,身份验证在基础结构项目中处理。它包含AspFormsAuthentication:IFormsAuthentication,AspMembershipAuthentication:ILocalAuthenticationService之类的实现。
由于他正在使用内置的成员资格提供程序,因此效果很好,但是我不是,所以我需要访问我的存储库。在我的方案中,将ILocalAuthenticationService和AspMembershipAuthentication实现放置在Services项目中会更好吗?
我在其他地方问过这个问题,有人回答:
伟大的。这是有道理的。但是我不知道从这里去哪里。案例研究中的代码:
public class AspMembershipAuthentication : ILocalAuthenticationService
{
public User Login(string email, string password)
{
User user = new User();
user.IsAuthenticated= false;
if (Membership.ValidateUser(email, password))
{
MembershipUser validatedUser = Membership.GetUser(email);
user.AuthenticationToken = validatedUser.ProviderUserKey.ToString();
user.Email = email;
user.IsAuthenticated = true;
}
return user;
}
public User RegisterUser(string email, string password)
{
MembershipCreateStatus status;
User user = new User();
user.IsAuthenticated = false;
Membership.CreateUser(email, password, email,
Guid.NewGuid().ToString(), Guid.NewGuid().ToString(),
true, out status);
if (status == MembershipCreateStatus.Success)
{
MembershipUser newlyCreatedUser = Membership.GetUser(email);
user.AuthenticationToken = newlyCreatedUser.ProviderUserKey.ToString();
user.Email = email;
user.IsAuthenticated = true;
}
else
{
switch (status)
{
case MembershipCreateStatus.DuplicateEmail:
throw new InvalidOperationException(
"There is already a user with this email address.");
case MembershipCreateStatus.DuplicateUserName:
throw new InvalidOperationException(
"There is already a user with this email address.");
case MembershipCreateStatus.InvalidEmail:
throw new InvalidOperationException(
"Your email address is invalid");
default:
throw new InvalidOperationException(
"There was a problem creating your account. Please try again.");
}
}
return user;
}
}
如果不使用成员资格提供程序,如何连接数据库以检查用户名和密码是否匹配以及其他可能的检查?
最佳答案
在基础结构层中,创建一个实现ILocalAuthenticationService并进行所需调用的类。
或者,如果ILocalAuthenticationService太ASP.NET-y(及其用户返回类型),则可能必须滚动自己的ILocalAuthenticationService变量并实现该变量。
然后,在需要时使用IoC容器解析ILocalAuthenticationService。