如果你想下载一些代码来看看它是如何完成的,你可以拿 nerdinner 的:http ://nerddinner.codeplex.com/
首先你需要确保你的 web.config 配置没问题
<connectionStrings>
<add name="XXXXXMembership" connectionString="data source=.\SQLEXPRESS;Initial Catalog=corpiq_membership;User Id=corpiq; Password=c0rp1q; Persist Security Info=true;" providerName="System.Data.SqlClient" />
<add name="CorpiqDb" connectionString="data source=.\SQLEXPRESS;Initial Catalog=corpiq;User Id=corpiq; Password=c0rp1q; Persist Security Info=true;" providerName="System.Data.SqlClient" />
</connectionStrings>
<membership>
<providers>
<clear/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="XXXXXMembership"
enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true"
maxInvalidPasswordAttempts="3" minRequiredPasswordLength="8" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="30"
passwordStrengthRegularExpression="^.*(?=.{8,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$" passwordFormat="Hashed" applicationName="/" />
</providers>
</membership>
如果一切正常,您应该能够启动 ASP.Net 配置工具,当您在 MVC 网站上时,女巫是锤子(红色)和解决方案资源管理器顶部的星球。使用该工具,您可以添加用户和角色。
在您应该能够简单地在您的控制器中添加这一行之后:
[Authorize(Roles = "Member, Delegate")]
我建议编写一个调用 Membership 方法的包装器,这样你就可以拥有自己的逻辑,这是我的:
public class AuthenticationService : IAuthenticationService
{
public bool IsValidLogin(string email, string password)
{
//Unlock user if it makes more than 30 minutes
CheckLocked(email);
return Membership.ValidateUser(email, password);
}
public void SignIn(string email, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
FormsAuthentication.SetAuthCookie(email, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
public string GetLoggedInUserName()
{
return Membership.GetUser() != null ? Membership.GetUser().UserName : string.Empty;
}
public MembershipCreateStatus RegisterUser(string email, string password, string role)
{
MembershipCreateStatus status;
Membership.CreateUser(email, password, email, Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true, out status);
if (status == MembershipCreateStatus.Success)
{
Roles.AddUserToRole(email, role);
}
return status;
}
public MembershipUserCollection GetAllUsers()
{
return Membership.GetAllUsers();
}
public string GeneratePassword()
{
var alphaCaps = "QWERTYUIOPASDFGHJKLZXCVBNM";
var alphaLow = "qwertyuiopasdfghjklzxcvbnm";
var numerics = "1234567890";
var special = "@#$";
var allChars = alphaCaps + alphaLow + numerics + special;
var r = new Random();
var generatedPassword = "";
for (int i = 0; i < MinPasswordLength - 1; i++)
{
double rand = r.NextDouble();
if (i == 0)
{
//First character is an upper case alphabet
generatedPassword += alphaCaps.ToCharArray()[(int)Math.Floor(rand * alphaCaps.Length)];
//Next one is numeric
rand = r.NextDouble();
generatedPassword += numerics.ToCharArray()[(int) Math.Floor(rand*numerics.Length)];
}
else
{
generatedPassword += allChars.ToCharArray()[(int)Math.Floor(rand * allChars.Length)];
}
}
return generatedPassword;
}
public int MinPasswordLength
{
get
{
return Membership.Provider.MinRequiredPasswordLength;
}
}
public string AdminRole
{
get { return "admin"; }
}
public string MemberRole
{
get { return "member"; }
}
public string DelegateRole
{
get { return "delegate"; }
}
public bool Delete(string email)
{
return Membership.DeleteUser(email);
}
public bool IsAdmin()
{
return Roles.IsUserInRole(AdminRole);
}
public bool IsMember()
{
return Roles.IsUserInRole(MemberRole);
}
public bool IsDelegate()
{
return Roles.IsUserInRole(DelegateRole);
}
public bool ChangePassword(string email, string oldPassword, string newPassword)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
if (String.IsNullOrEmpty(oldPassword)) throw new ArgumentException("Value cannot be null or empty.", "oldPassword");
if (String.IsNullOrEmpty(newPassword)) throw new ArgumentException("Value cannot be null or empty.", "newPassword");
// The underlying ChangePassword() will throw an exception rather
// than return false in certain failure scenarios.
try
{
var currentUser = Membership.Provider.GetUser(email, true);
return currentUser.ChangePassword(oldPassword, newPassword);
}
catch (ArgumentException)
{
return false;
}
catch (MembershipPasswordException)
{
return false;
}
}
public string ResetPassword(string email)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
var currentUser = Membership.Provider.GetUser(email, false);
return currentUser.ResetPassword();
}
public bool CheckLocked(string email)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
var currentUser = Membership.Provider.GetUser(email, false);
if (currentUser == null) return false;
if (!currentUser.IsLockedOut) return false;
if (currentUser.LastLockoutDate.AddMinutes(30) < DateTime.Now)
{
currentUser.UnlockUser();
return false;
}
return true;
}
public bool Unlock(string email)
{
if (String.IsNullOrEmpty(email)) throw new ArgumentException("Value cannot be null or empty.", "email");
var currentUser = Membership.Provider.GetUser(email, false);
if (currentUser == null) return false;
currentUser.UnlockUser();
return true;
}
public void CheckRoles()
{
if (!Roles.RoleExists(MemberRole)) Roles.CreateRole(MemberRole);
if (!Roles.RoleExists(AdminRole)) Roles.CreateRole(AdminRole);
if (!Roles.RoleExists(DelegateRole)) Roles.CreateRole(DelegateRole);
}
}
我不太确定您是否不了解女巫部分,但请让我们详细了解您的问题,也许我们可以提供更多帮助!我认为您需要先构建代码。
这是 EF 的一个良好开端(因此您可以在自己的数据库中编写自定义配置文件/用户):http ://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first -with-an-existing-database.aspx