为什么 [Authorize(Roles = "Admin")] 不能在 MVC 5 RTM 和 ASP.NET Identity 中工作? [英] Why isn't [Authorize(Roles = "Admin")] working in MVC 5 RTM with ASP.NET Identity?

查看:17
本文介绍了为什么 [Authorize(Roles = "Admin")] 不能在 MVC 5 RTM 和 ASP.NET Identity 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[Authorize(Roles = "Admin")] 是否在 MVC 5 RTM 中使用 ASP 开箱即用.NET 身份?

我运气不好.请注意,[Authorize][Authorize(Users = "AdminUser")] 工作正常,并且 AspNetUserRoles 和 AspNetRoles 表已按照我的预期填充,在 AdminUser 用户和 Admin 角色之间建立关系.这个问题似乎特定于角色.

解决方案

答案是UserManager 的 DbContext 必须启用延迟加载,以便用户角色在应用程序中正常显示,预期,方式.事实证明,并非我的所有代码都是开箱即用"的.我已经稍微自定义了我的 DbContext.希望将来 Microsoft 将通过确保集合加载了诸如 userDbContext.Users.Include(o => o.Roles).SingleOrDefault(...) 之类的内容来避免此集成错误.>

  • 做:ApplicationDbContext.Configuration.LazyLoadingEnabled = true;
  • 不要:ApplicationDbContext.Configuration.LazyLoadingEnabled = false;

请注意,如果您的代码中未设置 ApplicationDbContext.Configuration.LazyLoadingEnabled,则它默认为 true.所以去掉那行就像将它设置为 true 一样好.

这是我对禁用延迟加载时发生的情况的猜测,IdentityUser/ApplicationUser 对象的 Roles 属性为 null 或当 UserManager 或 UserStore 访问它时为空,因为该集合不是手动加载的.然后代码继续执行,就像没有为用户分配角色一样,而实际上该集合从未加载过.

啊,无声失败的香气.让代码只在事情看起来不正确时发出一些噪音.

Does [Authorize(Roles = "Admin")] work out of the box in MVC 5 RTM with ASP.NET Identity?

I've had no luck. Note that [Authorize] and [Authorize(Users = "AdminUser")] work just fine, and the AspNetUserRoles and AspNetRoles tables are populated as I would expect them to be, establishing a relationship between the AdminUser user and the Admin role. This issue seems specific to roles.

解决方案

And the answer is the UserManager's DbContext must have lazy loading enabled in order for user roles to manifest in the application in the usual, expected, way. As it turns out, not all of my code was "out of the box." I had customized my DbContext ever so slightly. Hopefully in the future Microsoft will sidestep this integration bug by ensuring the collection is loaded with something like userDbContext.Users.Include(o => o.Roles).SingleOrDefault(...).

  • DO: ApplicationDbContext.Configuration.LazyLoadingEnabled = true;
  • DO NOT: ApplicationDbContext.Configuration.LazyLoadingEnabled = false;

Note that if ApplicationDbContext.Configuration.LazyLoadingEnabled is not set in your code then it defaults to true. So leaving off that line is as good as setting it to true.

Etc.

Here's my guess at what is going on when lazy loading is disabled, the Roles property of the IdentityUser / ApplicationUser object is null or empty when the UserManager or UserStore accesses it because that collection was not manually loaded. The code then carries on like no roles have been assigned to the user when in fact that collection simply was never loaded.

Ah, the aroma of silent failure. Had the code only made some noise when things didn't look right.

这篇关于为什么 [Authorize(Roles = "Admin")] 不能在 MVC 5 RTM 和 ASP.NET Identity 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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