Ben*_*ury 18 roles asp.net-web-api asp.net-identity
我有一个用户个人帐户的.NET Web API项目.我可以使用标准模板AccountController注册用户.但是,我现在想要根据用户类型设置角色并将用户添加到角色.
DB中没有自动设置角色.如何设置角色以及如何将用户添加到角色?
我可以在此找到的唯一信息是基于旧的ASP.NET成员资格,因此未能为其设置存储过程.
已经在MSDN上搜索了论坛和教程,似乎无法找到Web API的示例.
Ant*_*Chu 23
您可以使用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");
}
Run Code Online (Sandbox Code Playgroud)
你说文档现在有点亮了你是对的.但我发现,一旦你使用了RoleManager和UserManager,API就很容易被发现了(但也许并不总是直观的,有时候你必须直接针对商店甚至数据库上下文运行查询).
我花了一段时间才弄清楚,但我终于明白了.安东尼请原谅我,但要重新发布一些代码,以便像我这样的愚蠢的开发人员能够理解.
在最新的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();
}
Run Code Online (Sandbox Code Playgroud)
你想要做的是用这个替换它:
// 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();
}
Run Code Online (Sandbox Code Playgroud)
现在当你发布它应该正确工作,但你可能会遇到另一个问题.在我这样做之后,我的回复抱怨了DB.
The model backing the <Database> context has changed since the database was created
Run Code Online (Sandbox Code Playgroud)
要修复此错误,我必须进入程序包管理器控制台并启用迁移.
Enable-Migrations –EnableAutomaticMigrations
Run Code Online (Sandbox Code Playgroud)
然后:
Add Migration
Run Code Online (Sandbox Code Playgroud)
最后:
Update-Database
Run Code Online (Sandbox Code Playgroud)
关于启用迁移的好帖子:http: //msdn.microsoft.com/en-us/data/jj554735.aspx
| 归档时间: |
|
| 查看次数: |
17545 次 |
| 最近记录: |