【问题标题】:ASP.NET Identity without Entity Framework没有实体框架的 ASP.NET 标识
【发布时间】:2016-08-20 03:33:07
【问题描述】:

是否可以在不使用实体框架的情况下使用新的 ASP.NET 标识,而使用您自己的方法?

我有一个使用普通 ADO.NET 进行数据访问的 MVC 项目。我想实现 ASP.NET 标识,但我想继续使用 ADO.NET 和存储过程。这是我选择的方式。

【问题讨论】:

标签: c# asp.net .net asp.net-mvc asp.net-identity


【解决方案1】:

我和你自己也有类似的要求,并且已经实现了一个纯 SQL Server 版本的 ASP.NET Identity 框架。

我首先创建了一个示例项目(使用实体框架),然后观察它创建的表。然后我将这些移植到 Visual Studio Sql 项目中。

接下来,我使用this link 提供有关哪些方法需要实现以及哪些方法与数据库交互的指导(注意:并非商店中的所有方法都可以/应该)。链接上的代码适用于 MySQL,但让我很好地理解了要实现的内容等。

我仍然拥有使用 Sql 为 ASP.Net Identity Framework 编写的代码。因此,如果我周末有时间,我会看看它的状态有多好,并可能将其上传到 github 并在此处更新链接。

但与此同时,请使用该链接 - 它也提供了良好的学习体验!

【讨论】:

  • 你的版本上传了吗?
【解决方案2】:

我正在使用 Asp.Net Identity 2.2.1。 我实现这一点的方式是创建自己的用户:

public class MyUser : IUser {...}

然后创建我自己的 UserStore: (实现您实现的接口所需的所有方法,并在这些方法上使用您的数据访问拉/插入数据。例如,我创建了另一个 dal 类,在该类上我使用dapper 访问数据库,我提供了示例我的用户存储中的一种方法,但您实现的所有其他方法都是相同的想法)

public class MyUserStore : IUserStore<MyUser>, IUserPasswordStore<MyUser>, IUserLockoutStore<MyUser, string>, IUserEmailStore<MyUser>
{
    public Task<MyUser> FindByNameAsync(string userName)
    { 
        MyUser muser = dal.FindByUsername(userName);

        if (muser != null)
            return Task.FromResult<User>(muser);

        return Task.FromResult<MyUser>(null);
    }
    //... all other methods
}

然后我的 dal.cs 上的方法看起来像这样:

public MyUser FindByUsername(string username)
{
    //pull user from the database however you want to based on the username, 
    //in my case here is where I used Dapper to query the db and return the User object with the data on it, but you can do it however you want.

    return myUser; //object with data on it
}

然后在我的 UserManager 上,我像这样设置用户存储:

public UserManager() : base(new MyUserStore())
{
    //anything else you need on the constructor
}

注意: 并非 MyUserStore 上的所有方法都需要访问数据库,因为其中很多都调用 FindUser... 方法或 UpdateUser 方法。比如:

public Task<int> IncrementAccessFailedCountAsync(MyUser user)
{
    //here I just updated the user object as I know that UpdateAsync() method will be called later.
    return Task.FromResult<int>(++user.FailedAttempts); 
}

【讨论】:

  • 能否分享代码ApplicationUserManagerApplicationSignInManager。我实现了MyUserStore,但在实现上述两个类时遇到了问题。我也在使用 dapper。
  • ApplicationUserManager: public class ApplicationUserManager: UserManager&lt;User&gt; { public ApplicationUserManager() : base(new MyUserStore()) { ... } ... }constructor 上,您必须将 UserStore 设置为您的实现作为参数,在本例中为 MyUserStore。我认为这是App User Manager中唯一重要的部分,在这里添加太长了;但我剩下的只是对 PasswordValidator、dataProtectionProvider 和 EmailService 的配置,但这与模板的代码相同
  • 您不需要对 ApplicationUserManager 进行太多更改。由于访问数据的代码是 UserStore 上的代码,所以你的实现就是这样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-26
  • 2017-01-06
  • 1970-01-01
相关资源
最近更新 更多