1

Need help how to declare parameters in User.Identity.IsAuthenticated ?

@if (User.Identity.IsAuthenticated)
{
    if (User.Identity.Name == "admin@admin.com")
    /*instead of User.Identity.Name, I want to use
    if(User.Identity.RoleID = 1)
    {
         Admin Login Successfull 
    }  
    else if(User.Identity.RoleID = 2)
    {
          User Login Successfull 
    }  

    Where to declare parameter "RoleID"*/

}
hutchonoid
  • 32,982
  • 15
  • 99
  • 104
Nabeel
  • 81
  • 1
  • 1
  • 10
  • This is a good thread. [Try this thread][1] [1]: http://stackoverflow.com/questions/18448637/how-to-get-current-user-and-how-to-use-user-class-in-mvc5 – Scott Jul 03 '15 at 07:20

2 Answers2

0

To get the roles of the currently logged in user use:

Roles.GetRolesForUser() 

Docs from MSDN for GetRolesForUser

Mivaweb
  • 5,580
  • 3
  • 27
  • 53
0

You could create an HtmlHelper extension method that you could use in your views like this:

@Html.LoggedInMessage(User)

This would avoid having the if else logic in your views, but it is worth noting with your current logic that there may be an instance of users belonging to more than one role unless this is restricted from your system.

public static MvcHtmlString LoggedInMessage(this HtmlHelper htmlHelper, IPrincipal user)
{
    var tb = new TagBuilder("span");
    if (user.Identity.IsAuthenticated)
    {
       if(user.IsInRole("Admin"))
       {
            tb.SetInnerText("Admin Login Successfull");
       }
       else if(user.IsInRole("OtherRole"))
       {
            tb.SetInnerText("User Login Successfull");
       }  
    }
    return new MvcHtmlString(tb.ToString());
}
hutchonoid
  • 32,982
  • 15
  • 99
  • 104