Multiple roles in 'User.IsInRole' [duplica

2019-02-22 07:17发布

This question already has an answer here:

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?

1条回答
Root(大扎)
2楼-- · 2019-02-22 08:00

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
}
查看更多
登录 后发表回答