关于asp.net mvc:在控制器中设置用户角色?

Setting user roles in controllers?

我需要能够在我的控制器中手动授权我的用户。
我从广告获得身份验证,然后在我的控制器中,
我想映射
从广告获得的用户ID,到应用程序的内部用户ID。
从UserRole表中获取userId,然后在控制器中进行设置,但是,
我不知道如何在控制器中设置角色?

我尝试在家庭控制器中执行以下操作:
HttpContext.User =新的System.Security.Principal.GenericPrincipal(User.Identity,roleName);

roleName设置为" Admin",但这似乎不起作用,因为它总是会失败授权。

请帮助?....


假设您在控制器方法中使用[Authorize],它将在操作方法之前运行,因此不会到达您必须设置角色名称的代码-需要在调用控制器之前进行设置。 >

向您的Global.asax添加这样的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
protected void Application_OnPostAuthenticateRequest(Object sender, EventArgs e)
{
    IPrincipal contextUser = Context.User;

    if (contextUser.Identity.AuthenticationType =="Forms")
    {
        // determine role name

        // attach to context
        HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(User.Identity, roleName);
        Thread.CurrentPrincipal = HttpContext.Current.User;
    }
}