您的位置:首页 > 编程语言 > ASP

asp.net identity(微软首推的身份验证)2.0分析-基于vs2015默认程序

2017-02-05 17:50 417 查看
因为总是感觉,asp.net identity用起来不太舒服,比如代码的扩展性,以及维护以后的版本,所以对其进行分析

下面进入正文:

在vs2015自带的默认程序中,App_Start/IdentityConfig.cs,通过ApplicationUserManager Create函数开始分析,函数主要内容如下

public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
..........

可以得出,该函数初始化,新建ApplicationUserManager类(该类自身),传入一个新建UserStore泛型类,并给该UserStore泛型类通过查看该类定义得出,传入的为DbContext context参数
而在Microsoft.AspNet.Identity.EntityFramework二进制dll中,UserStore新建用户的函数为

public async virtual Task CreateAsync(TUser user)
{
((UserStore<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim>) this).ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
((UserStore<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim>) this)._userStore.Create(user);
await ((UserStore<TUser, TRole, TKey, TUserLogin, TUserRole, TUserClaim>) this).SaveChanges().WithCurrentCulture();
}

可以看到对数据库的操作关键在于_userStore.Create,而_userStore字段的初始化为,
this._userStore = new EntityStore<TUser>(context);另外关于角色的管理,_roleStore字段为
this._roleStore = new EntityStore<TRole>(context);

EntityStore泛型中,通过内部调用EntityFramework对数据库进行操作

public void Create(TEntity entity)
{
this.DbEntitySet.Add(entity);
}


由此可知道,自己构建对数据库的操作,并和asp.net identity集成的方法

附上EntityStore的代码
namespace Microsoft.AspNet.Identity.EntityFramework
{
using System;
using System.Data.Entity;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;

internal class EntityStore<TEntity> where TEntity: class
{
public EntityStore(DbContext context)
{
this.Context = context;
this.DbEntitySet = context.Set<TEntity>();
}

public void Create(TEntity entity)
{
this.DbEntitySet.Add(entity);
}

public void Delete(TEntity entity)
{
this.DbEntitySet.Remove(entity);
}

public virtual Task<TEntity> GetByIdAsync(object id)
{
return this.DbEntitySet.FindAsync(new object[] { id });
}

public virtual void Update(TEntity entity)
{
if (entity != null)
{
this.Context.Entry<TEntity>(entity).State = EntityState.Modified;
}
}

public DbContext Context { get; private set; }

public DbSet<TEntity> DbEntitySet { get; private set; }

public IQueryable<TEntity> EntitySet
{
get
{
return this.DbEntitySet;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: