Creating Asp.net Identity user in Seed method of Db Initializer

∥☆過路亽.° 提交于 2019-11-28 07:35:11

In asp.net-identity-2 usermanager has non async methods to create.

var user = new ApplicationUser { Email = "admin@myemail.com", UserName = "admin@myemail.com" };
manager.Create(user, "Temp_123");

Same for rolemanager if you want to create "admin" role.

var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
roleManager.Create(new Role("admin"));

make the user admin

manager.AddToRole(user.Id, "admin");

Edit: As trailmax commented, Create() extension method comes in with Microsoft.AspNet.Identity namespace so do not forget using Microsoft.AspNet.Identity

TMG is correct - there are non-async methods available, and that's the easiest way in this particular case.

In general, however - when you you only have an async version of a function available to you, and you can't change the implementation of the method to be Async - you can create a task and wait for it synchronously.

So - instead of:

IdentityResult result = await manager.CreateAsync(user, "Temp_123");

You can code:

Task<IdentityResult> createTask = manager.CreateAsync(user, "Temp_123");
createTask.Wait();

Once the Wait has finished, the IdentityResult gets returned in

createTask.Result

You can also set a timeout on the Wait, like this:

Task<IdentityResult> createTask = manager.CreateAsync(user, "Temp_123");
if (!createTask.Wait(5000)) // Wait up to 5 seconds
{
   // We've timed out waiting - Do some error handling
}
else if (!createTask.Result.Succeeded)
{
  // Creating the user failed - Do some error handling
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!