我有一个使用个人帐户的.NET Web API项目。我可以使用标准的模板AccountController很好地注册用户。但是,我现在希望设置角色,并根据用户类型将用户添加到角色中。
数据库中没有自动设置的角色。如何设置角色以及如何将用户添加到角色?
我能找到的关于它的唯一信息是基于旧的ASP.NET成员资格,所以它失败的原因是没有为它设置存储过程。
我在MSDN上搜索了论坛和教程,但似乎找不到Web API的示例。
发布于 2014-02-13 01:19:27
您可以使用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就很容易被发现(但可能并不总是直观的,有时您必须直接对存储甚至db上下文运行查询)。
发布于 2014-05-29 10:33:16
我花了一段时间才弄明白,但我终于明白了。安东尼,请原谅,我要重发你的很多代码,这样像我这样的笨蛋开发人员就能理解了。
在最新的WebAPI2 (Visual Studio2013更新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();
}
现在,当你发布它时,它应该可以正常工作,但你可能会遇到进一步的问题。在我这样做之后,我的回应是抱怨DB。
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
https://stackoverflow.com/questions/21734345
复制相似问题