简体   繁体   English

user.isinrole 和 IsInRoleAsync(TUser user, string role) 的区别

[英]Difference between user.isinrole and IsInRoleAsync(TUser user, string role)

I am from a MVC background and Have just started working on ASP.Net Core.我来自 MVC 背景,刚刚开始研究 ASP.Net Core。 I am using Identity for Authentication.我正在使用身份验证。

For Authorization, In MVC I used to use:对于授权,在 MVC 中我曾经使用:

if(User.IsInRole("TestRole"))

In .Net Core, it seems like :在 .Net Core 中,它看起来像:

if(await IsInRoleAsync(User,"TestRole"))

From my initial impressions, It looks like MVC used to check in the claims where as Core checks from the database every single time.从我的初步印象来看,它看起来像 MVC 过去常常检查声明,而 Core 每次都从数据库中检查。 Am I correct in my assumption and that there is a DB trip every time the method is called in Core?我的假设是否正确,每次在 Core 中调用该方法时都会发生一次数据库行程?

If it is checking from the DB every time, would it not be an expensive operation and how is it any beneficial from the claims check?如果它每次都从数据库检查,这不是一项昂贵的操作,索赔检查有什么好处?

Identity now relies on the implementation by the UserStore<TUser> assigned to the UserManager<TUser> in use. Identity 现在依赖于分配给UserManager<TUser>使用的UserStore<TUser>的实现。 If you use the Entity Framework package, the UserStore<TUser> implementation always checks against the database.如果您使用实体框架包,则UserStore<TUser>实现始终检查数据库。

You can create your own UserStore<TUser> and check against the Controller.User 's Claims property or even perform some sort of caching after getting the claims the first time.您可以创建自己的UserStore<TUser>并检查Controller.UserClaims属性,甚至在第一次获得声明后执行某种缓存。 It's up to you what you use and how you cache/refresh those values.使用什么以及如何缓存/刷新这些值取决于您。

Notice that the previous implementations performed a synchronous database call if the Claims weren't already retrieved, so you should be thankful it now is IsInRoleAsync .请注意,如果 Claims 尚未检索到,之前的实现会执行同步数据库调用,因此您应该感谢它现在是IsInRoleAsync

From the Source Code you can see that It is using DbSet 从源代码中您可以看到它正在使用DbSet

public TContext Context { get; private set; }

private DbSet<TUser> UsersSet { get { return Context.Set<TUser>(); } }
private DbSet<TRole> Roles { get { return Context.Set<TRole>(); } }
private DbSet<TUserClaim> UserClaims { get { return Context.Set<TUserClaim>(); } }
private DbSet<TUserRole> UserRoles { get { return Context.Set<TUserRole>(); } }
private DbSet<TUserLogin> UserLogins { get { return Context.Set<TUserLogin>(); } }
private DbSet<TUserToken> UserTokens { get { return Context.Set<TUserToken>(); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM