如何在Web API MVC C#中扮演角色? [英] how to get role in web api mvc c#?

查看:42
本文介绍了如何在Web API MVC C#中扮演角色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用Web API获取所有角色,但未获得任何角色.我希望所有角色都以用户为明智.但是我无法在查询中扮演任何角色.你能帮我什么是问题.

I try to fetch all the roles using web api but didn't get any role. I want all roles by user wise. But I'm unable to get any role in my query. Can you help me what is problems.

这是我的代码:

var res = System.Web.Security.Roles.GetRolesForUser("abc.com").FirstOrDefault();
var r = System.Web.Security.Roles.GetAllRoles().ToList();

我尝试编写此代码,但是在我的数据库中没有任何作用,我添加了角色,还为此"abc.com"用户添加了角色.

i have try this code write but did't getting any role in my database i have added role and also add role for this 'abc.com' user.

推荐答案

正如您在上面的评论中提到的那样,您试图通过简单的 Controller 方法而非Api Controller获得用户的角色.因此,请在下面查看我的代码.

As you have mentioned in your comment above, you are trying to get the role by user in a simple Controller method not Api Controller. So check my code below.

假设您的控制器名称为 AdminController ,然后在下面添加这些代码.

Suppose your Controller name is AdminController, then there add these code below.

public class AdminController : Controller
{
 //rest code
 private ApplicationUserManager _userManager;

 public AdminController()
 {
 }

 public AdminController(ApplicationUserManager userManager)
 {
    UserManager = userManager;
 }
 public ApplicationUserManager UserManager
 {
    get
     {
      return _userManager ?? 
      HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
      }
    private set
      {
       _userManager = value;
      }
  }
  //then rest code, what ever you have 

  //Add this bellow code inside the Method, where you want to fetch the 
  //roles by username
  var myRoles = UserManager.FindByName("nirav@gmail.com").Roles;
  //then rest code

是的,您需要添加参考

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

就是这样!

这篇关于如何在Web API MVC C#中扮演角色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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