1

Closed

User.IsInRole(permission) not working

description

Hi.

I'm trying to use User.IsInRole(permission) on a custom cshtml but it does not work. For example, I have absolute confidence that current user has "Administrator" role but when I test it using IsInRole, the response allways is false. What is wrong? Why it does not work? I'm using Orchard v1.6. Thanks.
Closed Jun 9, 2013 at 6:24 AM by pszmyd
Everything is correct.

You're trying to use HttpContext.User.IsInRole, which is not going to work, as it has nothing to do with Orchard roles. This will always return false.

Fetch current user first by using IOrchardServices - var user = _services.WorkContext.CurrentUser and then do var hasRole = user.As<IUserRoles>().Contains(permission) instead.

comments

pszmyd wrote Jun 5, 2013 at 7:38 PM

Could you please provide some code snippet, example?

henryfelipe wrote Jun 5, 2013 at 11:33 PM

Hi pszmyd.

Above a sample of validation I'm doing againt user roles (this code is inside my custom cshtml page):

//Verify permission
bool itemPermission = false;
string[] permissions = strRolesPermited.Split(','); //string with roles allowed like "Administrator,Editor,Contributor"
foreach (string permission in permissions)
{
itemPermission = User.IsInRole(permission) ? true : itemPermission;

}

My problem is that all comparisons have as result false.

If you could help about what is happening, I'll be thankfull.

Regards,

Henry Felipe