0

您好,提前致谢

我迷路了,我不知道我的代码有什么问题,我一直在尝试遵循 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

    }


}

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

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

4

1 回答 1

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" />
    

对于自定义角色提供程序,其过程几乎相同

  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>
    

如果当您使用成员函数并且抛出 NotImplementedException 时,您知道您必须覆盖引发异常的方法。

于 2013-11-09T19:18:42.977 回答