【问题标题】:How to create roles and add users to roles in ASP.NET MVC Web API如何在 ASP.NET MVC Web API 中创建角色并将用户添加到角色
【发布时间】:2014-03-11 03:46:07
【问题描述】:

我有一个使用个人帐户的 .NET Web API 项目。我可以使用标准模板 AccountController 很好地注册用户。但是,我现在想根据用户类型设置角色并将用户添加到角色中。

数据库中没有自动设置角色。如何设置角色以及如何将用户添加到角色?

我能找到的唯一信息是基于旧的 ASP.NET 成员资格,所以它失败了,因为没有为它设置存储过程。

搜索了 MSDN 上的论坛和教程,但似乎找不到 Web API 的示例。

【问题讨论】:

    标签: asp.net-web-api roles asp.net-identity


    【解决方案1】:

    我花了一段时间才弄明白,但我终于明白了。 Anthony 请原谅我,但要重新发布你的很多代码,以便像我这样愚蠢的开发人员能够理解。

    在最新的 WebAPI2(Visual Studio 2013 Update 2)中,注册方法如下所示:

    // POST api/Account/Register
    [AllowAnonymous]
    [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
    
        var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
    
        IdentityResult result = await UserManager.CreateAsync(user, model.Password);
    
    
        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }
    
        return Ok();
    }
    

    你想要做的就是用这个替换它:

    // POST api/Account/Register
    [AllowAnonymous]
    [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
    
    
        IdentityResult result;
        using (var context = new ApplicationDbContext())
        {
            var roleStore = new RoleStore<IdentityRole>(context);
            var roleManager = new RoleManager<IdentityRole>(roleStore);
    
            await roleManager.CreateAsync(new IdentityRole() { Name = "Admin" });
    
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);
    
            var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
    
            result = await UserManager.CreateAsync(user, model.Password);
            await userManager.AddToRoleAsync(user.Id, "Admin");
    
        }
    
        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }
    
        return Ok();
    }
    

    现在,当您发布它时,它应该可以正常工作,但您可能会遇到进一步的问题。在我这样做之后,我的回复抱怨了数据库。

    The model backing the <Database> context has changed since the database was created
    

    要修复此错误,我必须进入包管理器控制台并启用迁移。

    Enable-Migrations –EnableAutomaticMigrations
    

    然后:

    Add Migration
    

    最后:

    Update-Database
    

    这里有一篇关于启用迁移的好帖子: http://msdn.microsoft.com/en-us/data/jj554735.aspx

    【讨论】:

    • 在控制器方法的中间实例化数据库上下文并不是一个好习惯。查看dependency inversion 原则。
    【解决方案2】:

    您可以使用 RoleManager 添加角色...

    using (var context = new ApplicationDbContext())
    {
        var roleStore = new RoleStore<IdentityRole>(context);
        var roleManager = new RoleManager<IdentityRole>(roleStore);
    
        await roleManager.CreateAsync(new IdentityRole { Name = "Administrator" });
    
        var userStore = new UserStore<ApplicationUser>(context);
        var userManager = new UserManager<ApplicationUser>(userStore);
    
        var user = new ApplicationUser { UserName = "admin" };
        await userManager.CreateAsync(user);
        await userManager.AddToRoleAsync(user.Id, "Administrator");
    }
    

    您说得对,现在文档有点轻。但是我发现,一旦您稍微使用了 RoleManager 和 UserManager,API 就会很容易发现(但可能并不总是直观,有时您必须直接针对存储甚至数据库上下文运行查询)。

    【讨论】:

    • 完美。感谢您的帮助!
    • @andrefadila 这段代码需要放在你想要创建新角色的代码中的任何位置。通常这些将在开发过程中设置,但可能在您的管理代码中。要将用户添加到角色,请在创建新用户时使用代码。
    • 我不太确定使用 web api 2 会去哪里。你能详细说明一下如何在一个新的 web api 2 项目上设置它吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-02
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多