Erma Isabel
Erma Isabel

Reputation: 2177

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

Upvotes: 0

Views: 4137

Answers (2)

James
James

Reputation: 82136

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 thatGetUserId is a function, not a property, therefore you need to actually call it

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

Upvotes: 1

Daniel Bj&#246;rk
Daniel Bj&#246;rk

Reputation: 2507

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")){
}

Upvotes: 1

Related Questions