Multiple roles in 'User.IsInRole'

Joan picture Joan · Oct 29, 2015 · Viewed 20.7k times · Source

I have 3 roles on my page, so I want to get access to link with two roles.

I try something like this

@if(User.IsInRole("Admin,User")) 
{
 //my code
}

Or this

@if (User.IsInRole("Admin") && User.IsInRole("User"))

{
 //my code
}

No one work's, the only one who I managed to works is this:

 @if (User.IsInRole("Admin")

But this last one it's only for one Role, How can I do that I want?

Answer

Christos picture Christos · Oct 29, 2015

No one work's, the only one who I managed to works is this:

This is reasonable, if you consider what the method IsInRole does.

Gets a value indicating whether the currently logged-on user is in the specified role. The API is only intended to be called within the context of an ASP.NET request thread, and in that sanctioned use case it is thread-safe.

That being said a user may has the role of Admin (so UserIsInRole("Admin") returns true) but may not has the role of User (so UserIsInRole("User") returns false). So User.IsInRole("Admin") && User.IsInRole("User") would evaluate to false.

That you might need is this:

// If the user's role is either admin or user then do something
@if (User.IsInRole("Admin") || User.IsInRole("User"))
{
    //my code
}