I have a project (MVC5 with SPA template) in which I need to copy functionality from another project. User.IsInRole() in Razor doesn't work.
Basically the roles are assign like this:
var currenIdentity = httpContext.User.Identity;
var roles = new List<string>();
roles.Add(Startup.AdministrationRole);
roles.Add(Startup.UserRole);
GenericPrincipal principal = new GenericPrincipal(currenIdentity, roles.ToArray());
httpContext.User = principal;
In Razor I have
@if (User.IsInRole(Startup.AdministrationRole))
{
@Html.ActionLink("Administrator »", "Config", "Admin", new { }, new { @class = "btn btn-default" })
}
In the original project when I debug, the User
property it's type is System.Security.Principal.GenericPrincipal
But when I debug the Razor View in my new project the User
property is another type: System.Security.Claims.ClaimsPrincipal
I'm curious why there is a difference and therefore I can't check the roles directly from System.Security.Claims.ClaimsPrincipal
?
GenericPrincipal
is assigned inside a custom filter.
Problem was that the Razor View is called from an [AllowAnonymous]
controller, which overrides my filter, therefore the assignment of GenericPrincipal
to the User is skipped.