ASP.NET MVC3和EF4.1 - 如何在运行aspnet_regsql后自定义成员资格?

时间:2011-09-07 18:48:17

标签: asp.net-mvc-3 custom-membershipprovider

我需要在我的社交网络应用程序中实现自定义成员身份,并将信息添加到现有数据库中的常规aspnet表中,如Country,Province,City,Birthdate等等。

我已经根据这篇文章Add ASP.NET Membership tables to my own existing database, or should I instead configure a separate ASP.NET membership database?运行了aspnet_regsql,并且已经尝试过这篇文章http://msdn.microsoft.com/en-us/library/ms366730.aspx#Y342但是我从覆盖方法中得到了一些构建错误,而且我想找到任何示例步骤使用MVC 3和EF4.1逐步执行。

无论如何,在运行aspnet_regsql之后,实现自定义成员资格方法的下一步是什么?你知道任何一步一步(简单)的教程来帮助我吗?谢谢你们!

4 个答案:

答案 0 :(得分:2)

将您的其他用户数据存储在您自己的“用户”表中。存储您想要的任何其他字段,并包含一个允许您将记录与成员资格用户关联的字段。不要使用会员表,只能通过会员提供商访问它们,以避免处理微软未来可能做出的任何变更。

答案 1 :(得分:1)

如果您想下载一些代码来了解它是如何完成的,您可以选择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

答案 2 :(得分:0)

你不会把这种东西放在会员资格中。你把它放在Profiles或你自己的数据库中。

答案 3 :(得分:0)

非常感谢您的所有答案,所有这些对我都有帮助,我发现这个链接对我有很大帮助,为您的答案添加信息,我想与社区分享,也许它可以帮助某人否则:

http://www.java2s.com/Tutorial/ASP.NET/0420__Authentication-Authorization/UsingASPNETMembership.htm