实现我自己的RoleProvider-and-MembershipProvider

时间:2013-11-09 12:50:15

标签: c# asp.net-mvc membership-provider asp.net-roles

您好,并提前致谢

我迷路了,我不知道我的代码有什么问题,而且我一直在努力遵循在 http://www.brianlegg.com/post/2011/05/09/Implementing-your-own-RoleProvider-and-MembershipProvider-in-MVC-3.aspx并进行更改以匹配我自己的数据库。

首先,这是我的数据库脚本(ssms)的相关部分

CREATE TABLE BFS.dbo.BFSSUSER(

ID              int IDENTITY(1,1),
RoleID          int,
Name            nvarchar(50)NOT NULL,
SiteName        nvarchar(50)NOT NULL,
UserPassword    nvarchar(20),

CONSTRAINT BFSSUSER_pk PRIMARY KEY (ID))


GO
USE BFS
GO

CREATE TABLE BFS.dbo.ROLE(
ID          int IDENTITY(1,1),
Name            nvarchar(50)NOT NULL


CONSTRAINT ROLE_pk PRIMARY KEY (ID),
CONSTRAINT ROLE_fk FOREIGN KEY (ID) REFERENCES BFSUSER(ID)) 

GO

好的,我正在尝试制作我的提供者并使用存储库类

我会将我的整个代码包含在其中,但是我会从错误的开始位置识别出错误 而且我不知道该怎么做

(我的所有if roleExists声明都是红色的并且让我疯狂(34个错误!!!),我已经尝试了几种组合让它们消失并且(基本上我很糟糕)任何所有的帮助都会很大赞赏(记得我的品牌打击asp.net新手,不知道什么是什么或意味着什么!!)

这是我的代码

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

    namespace BFS.Models
    {
        public class BFSRepository
        {
             private BFSEntities entities = new BFSEntities();

        private const string MissingRole = "Role does not exist";
        private const string MissingUser = "User does not exist";
        private const string TooManyUser = "User already exists";
        private const string TooManyRole = "Role already exists";
        private const string AssignedRole = "Cannot delete a role with assigned users";



        #region Properties

        public int NumberOfUsers
        {
            get
            {
                return this.entities.BFSUSERs.Count();
            }
        }

        public int NumberOfRoles
        {
            get
            {
                return this.entities.ROLEs.Count();
            }
        }

        #endregion

        #region Constructors

        public BFSRepository()
        {
            this.entities = new BFSEntities();
        }

        #endregion

        #region Query Methods

        public IQueryable<BFSUSER> GetAllUsers()
        {
            return from user in entities.BFSUSERs
                   orderby user.ID
                   select user;
        }

         public BFSUSER GetUser(int id)
        {
            return entities.BFSUSERs.SingleOrDefault(user => user.ID == id);
        }

        public BFSUSER GetUser(string userName)
        {
            return entities.BFSUSERs.SingleOrDefault(user => user.SiteName == userName);
        }

     FROM HERE ON DOWN IS WHERE ALL MY ERRORS START
     "entities does not contain a definition for 'Roles' etc etc missing assem ref

        public IQueryable<BFSUSER> GetUsersForRole(string Name)
        {
            return GetUsersForRole(ROLE(Name));
        }

        public IQueryable<BFSUSER> GetUsersForRole(int id)
        {
            return GetUsersForRole(GetRole(id));
        }

        public IQueryable<ROLE> GetUsersForRole(Roles role)
        {
            if (!ExistsROLE(role))
                throw new ArgumentException(MissingRole);

            return from user in entities.BFSUSERs
                   where user.RoleID == role.ID
                   orderby user.SiteName
                   select user;
        }

        public IQueryable<ROLE> GetAllRoles()
        {
            return from role in entities.ROLEs
                   orderby role.Name
                   select role;
        }

        public ROLE GetRole(int id)
        {
            return entities.ROLEs.SingleOrDefault(role => role.ID == id);
        }

        public ROLE GetRole(string name)
        {
            return entities.ROLEs.SingleOrDefault(role => role.Name == name);
        }

        public ROLE GetRoleForUser(string SiteName)
        {
            return GetRoleForUser(GetUser(SiteName));
        }

        public ROLE GetRoleForUser(int id)
        {
            return GetRoleForUser(GetUser(id));
        }

        public ROLE GetRoleForUser(User user)
        {
            if (!UserExists(user))
                throw new ArgumentException(MissingUser);

            return user.Role;
        }

        #endregion

        #region Insert/Delete

        private void AddUser(BFSUSER user)
        {
            if (BFSUSERExists(user))
                throw new ArgumentException(TooManyUser);

            entities.BFSUSERs.Add(user);
        }

        public void CreateUser(string name, string SiteName, string UserPassword, string roleName)
        {
            ROLE role = GetRole(roleName);

            if (string.IsNullOrEmpty(SiteName.Trim()))
                throw new ArgumentException("The user name provided is invalid. Please check the value and try again.");
            if (string.IsNullOrEmpty(name.Trim()))
                throw new ArgumentException("The name provided is invalid. Please check the value and try again.");
            if (string.IsNullOrEmpty(UserPassword.Trim()))
                throw new ArgumentException("The password provided is invalid. Please enter a valid password value.");
            if (!roleExists(role))
                throw new ArgumentException("The role selected for this user does not exist! Contact an administrator!");
            if (this.entities.BFSUSERs.Any(user => user.SiteName == SiteName))
                throw new ArgumentException("Username already exists. Please enter a different user name.");

            newUser = new User()
           {
               UserName = SiteName,
               Name = name,
               Password = FormsAuthentication.HashPasswordForStoringInConfigFile(UserPassword.Trim(), "md5"),
               RoleID = role.ID
           };

            try
            {
                AddUser(newUser);
            }
            catch (ArgumentException ae)
            {
                throw ae;
            }
            catch (Exception e)
            {
                throw new ArgumentException("The authentication provider returned an error. Please verify your entry and try again. " +
                    "If the problem persists, please contact your system administrator.");
            }

            // Immediately persist the user data
            Save();
        }

        public void DeleteUser( user)
        {
            if (!UserExists(user))
                throw new ArgumentException(MissingUser);

            entities.BFSUSERs.DeleteObject(user);
        }

        public void DeleteUser(string userName)
        {
            DeleteUser(GetUser(userName));
        }

        public void AddRole(Roles role)
        {
            if (RolesExists(role))
                throw new ArgumentException(TooManyRole);

            entities.Roles.AddObject(role);
        }

        public void AddRole(string roleName)
        {
            Role role = new Role()
            {
                Name = roleName
            };

            AddRole(role);
        }

        public void DeleteRole(Role role)
        {
            if (!RoleExists(role))
                throw new ArgumentException(MissingRole);

            if (GetUsersForRole(role).Count() > 0)
                throw new ArgumentException(AssignedRole);

            entities.Roles.DeleteObject(role);
        }

        public void DeleteRole(string roleName)
        {
            DeleteRole(GetRole(roleName));
        }

        #endregion

        #region Persistence

        public void Save()
        {
            entities.SaveChanges();
        }

        #endregion

        #region Helper Methods

        public bool UserExists(User user)
        {
            if (user == null)
                return false;

            return (entities.Users.SingleOrDefault(u => u.ID == user.ID || u.UserName == user.UserName) != null);
        }

        public bool RoleExists(Roles role)
        {
            if (role == null)
                return false;

            return (entities.BFSUSERs.SingleOrDefault(r => r.ID == role.ID || r.Name == role.Name) != null);
        }

        #endregion

    }


}

任何和所有帮助将不胜感激

特别向我解释或显示它何时需要是表名,变量名等。我很困惑,因为我的表名是角色,我正在做的是角色

1 个答案:

答案 0 :(得分:1)

通过几个步骤创建自定义成员资格提供程序:

  1. 创建一个继承自MembershipProvider(MVC3)或ExtendedMembershipProvider(MVC4)的类
  2. 让Visual Studio实现所有必需的成员,现在你有一个有很多成员的类,其中有throw new NotImplementedException();正文
  3. 现在很困难:确定你实际必须覆盖的方法。要获得基本功能,您需要:
    • public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
    • public override MembershipUser GetUser(string username, bool userIsOnline)
    • public override bool ValidateUser(string username, string password)
  4. 使用必要的用户管理代码填写上述方法的正文
  5. 配置web.config以使用您的自定义成员资格提供程序:

    <membership defaultProvider="CurrentProvider" userIsOnlineTimeWindow="10">
      <providers>
        <add name="CurrentProvider" Type="YOUR.WEBAPP.PROVIDERS.CustomMembershipProvider" />
      </providers>
    </membership>
    

    对于MVC4必须添加或设置以下AppSettings:

    <add key="enableSimpleMembership" value="false" />
    <add key="autoFormsAuthentication" value="false" />
    
  6. 对于自定义角色提供程序,它几乎与程序相同

    1. 见上文,除了:使用RoleProvider(MVC3和4)进行继承
    2. 见上文
    3. 见上文,除了:所需的方法是:
      • public override bool IsUserInRole(string username, string roleName)
      • public override string[] GetRolesForUser(string username)
    4. 见上文
    5. <roleManager defaultProvider="CurrentProvider" enabled="true">
        <providers>
          <add name="CurrentProvider" type="YOUR.WEBAPP.PROVIDERS.CustomRoleProvider" />
        </providers>
      </roleManager>
      
    6. 如果你使用隶属函数并抛出NotImplementedException,你就知道你必须覆盖抛出异常的方法。