实体框架代码首先与SimpleMembershipProvider [英] Entity Framework Code First with SimpleMembershipProvider

查看:165
本文介绍了实体框架代码首先与SimpleMembershipProvider的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个解决方案中有两个项目:

I have two projects inside one solution:


  1. foo.Domain(类库,我的实体和DBContext都在这里) li>
  2. foo.WebUI(ASP.NET MVC 4.5,空模板)

Inside foo.Domain i使用实体框架创建我的实体并将其转换为实际的数据库。

Inside foo.Domain i create my entities and translate them into actual database using Entity Framework.

我一直在网上搜索如何使用实体框架代码首先创建具有注册,登录功能等的自定义会员功能,并在ASP.NET MVC中构建simplemembershipprovider 4,但是foo.WebUI和迁移的大部分demo在线使用实体框架都在foo.WebUI中,而不使用foo.Domain类库,如果我这样做,我将最终在两个单独的迁移内foo.Domain(其他实体)和foo.WebUI(用户+角色实体)。我很困惑我应该做什么,希望我说的话是有道理的。

I've been searching online on how I can create a custom membership feature with register, login functions etc using entity framework code first and built in simplemembershipprovider in ASP.NET MVC 4, but most of the demo online used entity framework inside foo.WebUI and migrations are all inside foo.WebUI without using a foo.Domain class library, if i do it that way, i am going to end up having two separate migrations inside foo.Domain(other entities) and foo.WebUI(user+role entities). I am very confused to what I should do, hope what i say makes sense.

推荐答案

假设你有foo.Domain以下表将管理安全措施:

Assuming that you have in foo.Domain the following tables that will manage the security things:


  1. 用户(至少拥有Id,UserName,Password和IsActive)

  2. 角色(Id,角色名称)

  3. UserRoles(拥有RoleId,UserId)

然后您可以执行以下操作:

then you can do the following:

1-添加一个类调用它(CustomMembership),其中包含以下

1- add a class call it (CustomMembership) containing the following

2-添加引用到WebMatrix.WebData以便使用简单的会员提供者

2- add refernece to WebMatrix.WebData in order to use the simple membership provider

 public class CustomMembership : SimpleMembershipProvider
    {

        public override bool ValidateUser(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                return false;
            using (var context = new Entities()) // Entities is your Context
            {
                string encryptedPassword = Encrypt(password); // Encryt is used for comparing the entered password with the encrypted password stored in db
                var item = context.Users.Where(t => t.UserName.ToLower() == username.ToLower()
                    && t.Password == encryptedPassword
                    && t.IsActive).FirstOrDefault();
                return item != null;

            }
        }
    }

添加类CustomRoleManager包含以下内容:

3- add class called CustomRoleManager contianing the following:

public class CustomRoleManager : SimpleRoleProvider
    {
        public override bool IsUserInRole(string username, string roleName)
        {
            using (var context = new Entities())
            {
                var result = context.UserRoles.FirstOrDefault(t => t.Role.Name == roleName
                    && t.User.UserName.ToLower() == username.ToLower()
                    && t.User.IsActive);
                return result != null;
            }
        }

        public override string[] GetAllRoles()
        {
            using (var context = new Entities())
            {
                var result = context.Roles.Select(t => t.Name).ToArray();
                return result;
            }
        }

        public override string[] GetRolesForUser(string username)
        {
            using (var context = new Entities())
            {
                var result = (from ur in context.UserRoles
                              join u in context.Users on ur.UserId equals u.Id
                              join r in context.Roles on ur.RoleId equals r.Id
                              where u.UserName.ToLower() == username.ToLower()
                              && u.IsActive
                              select r.Name).ToArray();
                return result;
            }
        }
    }

4-添加以下内容Web.Config文件,请注意,您应该添加类的完整路径,这里我放foo.WebUI

4- add the following in the Web.Config file, note that you should add the full path of the classes, here i put foo.WebUI

这一步是告诉你的应用程序使用自定义成员资格和自定义角色管理器

this step is to tell your application to use the custom membership and custom role manager

<roleManager enabled="true" defaultProvider="CustomRoleManager" cacheRolesInCookie="true">
      <providers>
        <clear />
        <add name="CustomRoleManager" type="foo.WebUI.CustomRoleManager" />
      </providers>
    </roleManager>
    <membership defaultProvider="CustomMembership" userIsOnlineTimeWindow="10">
      <providers>
        <clear />
        <add name="CustomMembership" type="foo.WebUI.CustomMembership" connectionStringName="ConnectionString" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" applicationName="/" />
      </providers>
    </membership>

5-也许您需要在web.config文件的应用程序设置中添加以下密钥,以避免错误

5- maybe you need to add the following keys in the app settings in web.config file to avoid errors

<add key="enableSimpleMembership" value="false" />
<add key="autoFormsAuthentication" value="false" />

希望这将有助于您

这篇关于实体框架代码首先与SimpleMembershipProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆