MVC 5 - 角色 - IsUserInRole 和将用户添加到角色 [英] MVC 5 - Roles - IsUserInRole and Adding user to role

查看:31
本文介绍了MVC 5 - 角色 - IsUserInRole 和将用户添加到角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 MVC4 中,我使用 Roles.IsUserInRole 来检查给定用户是否处于某个角色.但是,使用 MVC5 我不能再这样做了...

In MVC4 i used Roles.IsUserInRole to check if a given user is in some role. However, with MVC5 i can't do it anymore...

起初,它要求我在 web.config 中启用 RoleManager,但后来我发现微软从 Web.Security 转移到 Microsoft.AspNet.Identity.

At first, it asked me to enable RoleManager at the web.config but then i discovered that microsoft moved away from Web.Security to Microsoft.AspNet.Identity.

我现在的问题是,对于 Microsoft.AspNet.Identity,我如何执行类似于 Roles.IsUserInRole 的操作?和/或创建角色和用户之间的关系.

My question now is, with Microsoft.AspNet.Identity how do i do an action similar to Roles.IsUserInRole? And/or create a relation between the Role and the User.

顺便说一下,我仍在尝试了解新的身份验证方法(ClaimsIdentity?).

By the way, i'm still trying to understand the new authentication methods (ClaimsIdentity?).

推荐答案

您应该阅读 http://typecastexception.com/post/2014/04/20/ASPNET-MVC-and-Identity-20-Understanding-the-Basics.aspx 了解基础知识身份 2.0!

You should read http://typecastexception.com/post/2014/04/20/ASPNET-MVC-and-Identity-20-Understanding-the-Basics.aspx for the basics of Identity 2.0!

还有一个完整的演示项目可以帮助您入门:https://github.com/TypecastException/AspNet-Identity-2-With-Integer-Keys

There's also a complete demo project to get you started: https://github.com/TypecastException/AspNet-Identity-2-With-Integer-Keys

如果你以此为基础建立你的身份基础,你最终会得到这样的结果:

If you take this as the basis for your Identity foundation you'll end up with something like this:

var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
const string name = "YourUsername"
const string roleName = "Admin";

var user = userManager.FindByName(name);
//check for user roles
var rolesForUser = userManager.GetRoles(user.Id);
//if user is not in role, add him to it
if (!rolesForUser.Contains(role.Name)) 
{
    userManager.AddToRole(user.Id, role.Name);
}

这篇关于MVC 5 - 角色 - IsUserInRole 和将用户添加到角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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