1

我需要在我的社交网络应用程序中实现自定义成员资格,并将信息添加到现有数据库中的常规 aspnet 表中,例如国家、省、城市、出生日期等。

我已经运行了 aspnet_regsql,基于这篇文章Add ASP.NET Membership tables to my own existing database,还是应该配置一个单独的 ASP.NET 成员数据库?并且已经尝试关注这篇文章http://msdn.microsoft.com/en-us/library/ms366730.aspx#Y342但我从覆盖的方法中得到了一些构建错误,实际上我想找到任何示例步骤-逐步使用 MVC 3 和 EF4.1。

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

4

4 回答 4

2

将您的附加用户数据存储在您自己的用户表中。存储您想要的任何其他字段,并包括一个允许您将记录与会员用户相关联的字段。远离成员资格表,仅通过成员资格提供程序访问它们,以避免处理 Microsoft 将来可能在后台进行的任何更改。

于 2011-09-07T19:31:42.473 回答
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

于 2011-09-07T21:22:32.687 回答
0

你不要把这种东西放在会员资格中。您将其放入Profiles或您自己的数据库中。

于 2011-09-07T18:50:43.430 回答
0

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

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

于 2011-09-08T04:38:32.213 回答