我花了一段时间才弄明白,但我终于明白了。 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