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

查看:233
本文介绍了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?).

推荐答案

您应该读<一个href=\"http://typecastexception.com/post/2014/04/20/ASPNET-MVC-and-Identity-20-Understanding-the-Basics.aspx\">http://typecastexception.com/post/2014/04/20/ASPNET-MVC-and-Identity-20-Understanding-the-Basics.aspx用于Identity 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!

还有一个完整的演示项目,让你开始:
<一href=\"https://github.com/TypecastException/AspNet-Identity-2-With-Integer-Keys\">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天全站免登陆