Andarta Andarta - 1 year ago 93 Question

How do I get User's Role within code portion of _LoginPartial?

I am using MVC Entity Framework and I need to get a user's role within the _LoginPartial for some role-specific functionality within the nav bar. What is the best way to get that there?

I've tried using

Dim myRoles = Roles.GetRolesForUser()
, but that comes up with nothing. Which is wrong, because I use role-specific functionality elsewhere and that works fine.

Following the link in Marco's comment, it mentions using ClaimsIdentity, but for me it says ClaimsIdentity is not declared (Rick left a comment there this past August explaining it's not working for him like something changed in the past 2 years).

I had also tried this, which is similar to code in a controller I have elsewhere which does work:

Dim context As IOwinContext = New OwinContext
Dim manager = New AppUserManager(New UserStore(Of AppUser(context.Get(Of MyAppIdentityDbContext)()))
Dim userInfo = manager.FindById(curUserID)
Dim userRole As String = userInfo.Roles(0).RoleId
myRole = db.Roles.Where(Function(x) x.Id = userRole).FirstOrDefault().Name

But at runtime I get an error on the "Dim manager" line that says

An exception of type 'System.ArgumentNullException' occurred in
Microsoft.AspNet.Identity.EntityFramework.dll but was not handled in
user code Additional information: Value cannot be null.

I have no idea what value it's talking about.

Answer Source

Thanks to Marco's help and the other question he linked, I got it using the following code:

@Imports Microsoft.AspNet.Identity
@Imports System.Security.Claims
    Dim db = New MyAppIdentityDbContext
    Dim curUserID = User.Identity.GetUserId()
    Dim myFirstName As String = (From users In db.Users Where users.Id = curUserID Select users.FirstName).FirstOrDefault
    Dim myRole As String = ""
    If curUserID IsNot Nothing AndAlso curUserID <> "" Then
        Dim userID = CType(User.Identity, ClaimsIdentity)
        Dim claims = userID.Claims
        Dim roleType = userID.RoleClaimType
        Dim myRoles = claims.Where(Function(c) c.Type = roleType).ToList()
        myRole = (myRoles.FirstOrDefault.ToString)
        'Here myRole contains whole https string - need to strip it to actual value
        Dim lastInd = myRole.LastIndexOf(" ")
        myRole = myRole.Substring(lastInd + 1, myRole.Length - (lastInd + 1))
    End If
End Code
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download