简体   繁体   English

在Microsoft.AspNet.Identity中使用UserManager和RoleManager;

[英]Using UserManager and RoleManager in Microsoft.AspNet.Identity;

I've used this before, and I can't for the life in me figure what's going wrong. 我以前用过这个,我不能为我生活中的生活弄明白什么是错的。

@using System.Data.Entity;
@using Microsoft.AspNet.Identity;
@using Microsoft.AspNet.Identity.EntityFramework;


using(ApplicationDbContext db = new ApplicationDbContext())
{
   var rm = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
   var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

   var user = User.Identity.GetUserId();

        if(user != null)
        {
            string role = "Admin";
            if (!rm.RoleExists(role))
            {
                var roleResult = rm.Create(new IdentityRole(role));
                if (!roleResult.Succeeded) { //error stuff
                };
            }
            if (!um.IsInRole(user, role))
            {
                um.AddToRole(user, role);
            }
        }
}

When I run this I skip past the creating a role element (because I've already added this to the database), but when it gets to the 'is the user in role of Admin' bit, the line um.AddToRole(user, role) is run, but then I receive an error, stating that I have a violation because I am trying to duplicate the key. 当我运行这个时,我跳过创建一个角色元素(因为我已经将它添加到数据库中),但当它到达'是管理员角色的用户'位时,行um.AddToRole(用户,运行,但后来我收到一个错误,说明我有违规,因为我试图复制密钥。

I don't understand why the program when debugged says "there is no user with this name which has a role of Admin", and a fraction later when it tries to add that role, I'm presented with "Hey, that user already has a role of Admin and you can't add it again" 我不明白为什么调试时的程序说“没有这个名字的用户具有Admin的角色”,稍后当它试图添加该角色时,我会看到“嘿,那个用户已经有Admin的角色,你不能再添加它“

Before when I used RoleProviders I had to change my web.config and add info into there, but I haven't done this, because I don't have to!? 在我使用RoleProviders之前,我必须更改我的web.config并将信息添加到那里,但我没有这样做,因为我没有!?

It's probably very simple but I'm stuck. 它可能很简单,但我被卡住了。

Just for clarity how do I check if the currently logged in user belongs to the role "Admin" with AspNet.Identity. 为了清楚起见,我如何检查当前登录的用户是否属于具有AspNet.Identity的角色“Admin”。

Kind regards 亲切的问候

Ok so the problem turns out that turning lazing loading off causing this problem. 好吧所以问题是关闭转动lazing负载导致这个问题。 I updated the Microsoft Identity to 2.0 but still no joy. 我将Microsoft身份更新为2.0,但仍然没有乐趣。 Apparently it's a known bug which they are addressing. 显然,这是他们正在解决的已知错误。

Not ideal as I always turn lazy loading off. 不太理想,因为我总是把懒人装掉。 It's not a massive application, so performance isn't an issue. 这不是一个庞大的应用程序,因此性能不是问题。 Just so all are aware. 大家都知道。

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

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