Setting roles by using GenericPrincipal instance

2019-05-30 14:35发布

问题:

Recently I asked a question about how to use ajax calls to authenticate user in asp.net mvc, and I got my answer.

But then is decided to use 'Roles' property of 'GenericPrincipal' class

so I changed my code as follow to contain 'Roles':

HttpContext.User = new System.Security.Principal.
                    GenericPrincipal(new System.Security.Principal.GenericIdentity(login.LoginName),
                     userRole);

In my site.master view, I check to see which kind of roles users belongs to and I show appropriate menu, but when I watch 'HttpContext.Current.User.Identity' values during debugging, I see m_roles=string[0] and 'IsInRole("Admin")' returns false.

How could it be fixed?

回答1:

Try setting the current thread principle:

   System.Threading.Thread.CurrentPrincipal = principal;

as is shown here: http://social.msdn.microsoft.com/forums/en-US/Vsexpressvcs/thread/5f9735a9-096b-47af-963d-e95130cad6b4