没有实体框架的ASP.NET身份 [英] ASP.NET Identity without Entity Framework

查看:41
本文介绍了没有实体框架的ASP.NET身份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to use the new ASP.NET Identity without using Entity Framework and instead use your own methods?

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

I have an MVC project that uses plain ADO.NET for data access. I want to implement ASP.NET identity but I would like to continue to use ADO.NET and stored procedures. This is the way that I have chosen to go.

推荐答案

我正在使用Asp.Net Identity 2.2.1.我实现此目标的方法是创建自己的用户:

I am using Asp.Net Identity 2.2.1. The way I implemented this was by creating my own User:

public class MyUser : IUser {...}

然后创建我自己的UserStore:(实施您实现的接口所需的所有方法,并在这些方法上使用您的数据访问权限来拉入/插入数据.例如,我创建了另一个dal类,在其中使用了

Then create my own UserStore: (Implement all the methods required by the interfaces you implemented, and on those methods pull/insert the data using your data access. For example I created another dal class on which I use dapper to access the database, I provided the example of one method in my user store, but it is the same idea for all other methods you implement)

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上的方法如下所示:

Then the method on my dal.cs looks something like this:

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上设置用户存储,如下所示:

Then on my UserManager I set the user store like this:

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

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

NOTE: Not all the methods on MyUserStore need to access the database, because a lot of them call the FindUser... methods or the UpdateUser method. So for example:

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); 
}

这篇关于没有实体框架的ASP.NET身份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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