简体   繁体   中英

Get Logged in User Role: Asp.net MVC5

I have a doubt. I am using Asp.net mvc5 in VS2013. 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?

public class ApplicationUser : IdentityUser

This should work in the 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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