Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/268.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何向登录用户添加和启用OWIN角色?_C#_.net_Asp.net Mvc_Owin - Fatal编程技术网

C# 如何向登录用户添加和启用OWIN角色?

C# 如何向登录用户添加和启用OWIN角色?,c#,.net,asp.net-mvc,owin,C#,.net,Asp.net Mvc,Owin,我正在使用MVC5和OWIN身份验证。向登录用户添加角色时,只有用户重新登录后,该角色才会生效: [Authorize(Roles = "Role1")] public async Task<ActionResult> Action() { var currentUser = AuthenticationManager.User; var currentUserId = currentUser.Identity.GetUserI

我正在使用MVC5和OWIN身份验证。向登录用户添加角色时,只有用户重新登录后,该角色才会生效:

    [Authorize(Roles = "Role1")]
    public async Task<ActionResult> Action()
    {
        var currentUser = AuthenticationManager.User;
        var currentUserId = currentUser.Identity.GetUserId();
        var result = await UserManager.AddToRoleAsync(currentUserId, "Role2"); //result confirms role added 

        return RedirectToAction("AnotherAction", "Controller");
    }

    // not accessible until relog
    [Authorize(Roles = "Role2")]
    public ActionResult AnotherAction()
    {
        return View();
    }
[授权(Roles=“Role1”)]
公共异步任务操作()
{
var currentUser=AuthenticationManager.User;
var currentUserId=currentUser.Identity.GetUserId();
var result=await UserManager.AddToRoleAsync(currentUserId,“Role2”);//结果确认添加了角色
返回重定向到操作(“另一个操作”、“控制器”);
}
//在重新登录之前不可访问
[授权(Roles=“Role2”)]
公共行动结果另一项行动()
{
返回视图();
}

如何使角色更改立即生效?

我认为AddUserToRole方法在数据库级别执行分配。虽然这可能也需要发生,但您需要做的是刷新当前标识

简短回答:将原则抛给索赔人,将身份抛给索赔人。然后你可以添加索赔

 ClaimsPrincipal currentPrincipal = (ClaimsPrincipal)this.User;
 ClaimsIdentity currentIdentity = (ClaimsIdentity)currentPrincipal.Identity;

 currentIdentity.AddClaim(new Claim(ClaimTypes.Role, "Role2"));

在应用roleThx Jonesy之后,你可以签下并重新注册,这确实有效。这样做有什么可能的缺点吗?不是很容易想到的。他们的会话过期将被重置,但这可能不是问题。如果您遇到问题,请告诉我,这对我的未来也会很有帮助:)谢谢您的回答David,但它看起来像System.Web.Mvc.Controller.User没有公共setter,因此我无法以这种方式应用新标识。有没有关于如何处理ClaimsPrincipal的建议?@milter,我更新了代码示例。有一个ide来编写这些东西总是有帮助的。希望有帮助!