简体   繁体   English

登录用户角色:Asp.net MVC5

[英]Get Logged in User Role: Asp.net MVC5

I have a doubt. 我有个疑问。 I am using Asp.net mvc5 in VS2013. 我在VS2013中使用Asp.net mvc5。 When the user is logged in, username of the logged in user can be identified using, 当用户登录时,可以使用以下方式识别登录用户的用户名,

    User.Identity.GetUserId

But i couldn't be able to identify the role of the user in the view page. 但我无法在视图页面中识别用户的角色。

I tried the following: 我尝试了以下方法:

    @{
        var store = new Microsoft.AspNet.Identity.EntityFramework.UserStore<RaspberryPi.Models.ApplicationUser>(new RaspberryPi.Models.ApplicationDbContext());
        var manager = new Microsoft.AspNet.Identity.UserManager<RaspberryPi.Models.ApplicationUser>(store);
        var l = manager.IsInRole(User.Identity.GetUserId, "Moderator");
    }

But resulted in error. 但导致错误。

    CS1928: 'Microsoft.AspNet.Identity.UserManager<RaspberryPi.Models.ApplicationUser>' does not contain a definition for 'IsInRole' and the best extension method overload 'Microsoft.AspNet.Identity.UserManagerExtensions.IsInRole<TUser>(Microsoft.AspNet.Identity.UserManager<TUser>, string, string)' has some invalid arguments

How can i do that? 我怎样才能做到这一点?

Please help, Thanks 请帮忙,谢谢

Does your ApplicationUser derive from IdentityUser? 您的ApplicationUser是否派生自IdentityUser?

public class ApplicationUser : IdentityUser

This should work in the cshtml 这应该在cshtml中工作

@{
    var context = new RaspberryPi.Models.ApplicationDbContext();          
    if (context.Users.Any(u => u.UserName == User.Identity.Name))
    {
        var store = new Microsoft.AspNet.Identity.EntityFramework.UserStore<applicationuser>();
        var manager = new Microsoft.AspNet.Identity.UserManager<applicationuser>(store);
        ApplicationUser user = manager.FindByName<applicationuser>(User.Identity.Name);
        if (manager.IsInRole(user.Id, "Moderator") == true)
        {
        // Do whatever you want...
        }
    }

Or if you want to do it the simple way just do this. 或者,如果你想这样做,只需这样做。

@if (User.IsInRole("Moderator")){
}

The exception is pretty self explanatory really, the parameters you are providing do not tie up with the IsInRole extension method. 异常是非常自我解释的,您提供的参数不会与IsInRole扩展方法相关联。

The problem (assuming your code is exactly as you have shown) is that GetUserId is a function , not a property, therefore you need to actually call it 问题(假设您的代码完全如您所示)是GetUserId是一个函数 ,而不是属性,因此您需要实际调用它

manager.IsInRole(User.Identity.GetUserId(), "Moderator");

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

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