为什么不是[授权(角色="联系")]在MVC 5 RTM正在与ASP.NET身份? [英] Why isn't [Authorize(Roles = "Admin")] working in MVC 5 RTM with ASP.NET Identity?

查看:179
本文介绍了为什么不是[授权(角色="联系")]在MVC 5 RTM正在与ASP.NET身份?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确实 [授权(角色=管理员)] 制定出在MVC 5 RTM的盒子的 ASP.NET身份

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

我有没有运气。需要注意的是 [授权] [授权(用户=管理用户)] 工作得很好,和AspNetUserRoles和AspNetRoles表填充,因为我希望他们是,建立管理用户的用户和管理员角色之间的关系。这个问题似乎特定的角色。

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.

推荐答案

和答案是在的UserManager的的DbContext必须延迟加载,以便启用作为用户角色在应用程序清单在平时,预计,方法。事实证明,不是所有的我的code的是开箱即用。我已经定制了自己的DbContext非常轻微。希望将来微软将通过确保收集回避这个集成的bug装有类似 userDbContext.Users.Include(O = GT; o.Roles).SingleOrDefault(...)

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(...).


  • 请: ApplicationDbContext.Configuration.LazyLoadingEnabled = TRUE;

  • 请不要: ApplicationDbContext.Configuration.LazyLoadingEnabled = FALSE;

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

请注意,如果 ApplicationDbContext.Configuration.LazyLoadingEnabled 在code未设定则默认为真正。所以,离开了该行作为其设置为好真正

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.

下面是我在上的是什么时,延迟加载被禁用,角色的属性 IdentityUser /去猜测 ApplicationUser 对象为空或空当的UserManager或UserStore访问它,因为没有手动加载该集合中。就像没有角色已分配到事实,收集根本从未加载在用户的code,然后进行。

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.

嗯,无声故障的香气。有code只作了一些噪音,当事情看起来并不正确。

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

这篇关于为什么不是[授权(角色="联系")]在MVC 5 RTM正在与ASP.NET身份?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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