12

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?

Joan
  • 147
  • 1
  • 1
  • 7
  • 1
    What do you mean by not working? `@if (User.IsInRole("Admin") && User.IsInRole("User"))` looks perfectly fine to me (Assuming the comma separated roles is not a valid way to check roles). – Rob Oct 29 '15 at 22:16
  • The comma delimited expectation likely comes from the `Authorize(Roles="x,y")` [syntax here](https://learn.microsoft.com/en-us/aspnet/core/security/authorization/roles?view=aspnetcore-6.0#adding-role-checks) – StuartLC Aug 19 '22 at 12:01

1 Answers1

29

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
}
Christos
  • 53,228
  • 8
  • 76
  • 108
  • So I try @if (User.IsInRole("Admin") | User.IsInRole("User")) – Joan Oct 29 '15 at 22:24
  • @Joan I am glad that I helped :) – Christos Oct 29 '15 at 22:28
  • 7
    _"a user can not be in two roles"_ - please clarify in which authentication framework this is the case (in this case it looks like the the WebMatrix SimpleRoleProvider, if that's even true). Many, if not all other role providers do support a user being in multiple roles at once. There's for example also the method `GetRolesForUser()`. – CodeCaster Oct 29 '15 at 22:39
  • 4
    I know this is a couple of years old but in case anyone else stumbles onto this, "That being said a user can not be in two roles." is a totally false statement. The default EntityFramework User object even has an `ICollection` on it, https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.entityframework.identityuser(v=vs.108).aspx – nurdyguy Jul 18 '17 at 20:57
  • 1
    @nurdyguy Thanks for noting this! I just corrected it correspondingly. – Christos Jul 18 '17 at 21:59