简体   繁体   English

将用户添加到存在的角色时,任务被取消

[英]The Task is cancelled When adding a user to a role that exists

At the present I am trying to assign a role to a user the role table looks like following目前我正在尝试为用户分配角色,角色表如下所示

Role Id角色 ID Name姓名 NormalizedName标准化名称
59f5238-818e-40f9-b95a-fc65db67f253 59f5238-818e-40f9-b95a-fc65db67f253 Parent家长 Parent家长

My User table is我的用户表是

Id ID First Name Surname
b3e9d5ec-1ddf-4e57-bf00-1afc2e7f0582 b3e9d5ec-1ddf-4e57-bf00-1afc2e7f0582 Parent家长 One

The role is also being created fine.这个角色也被创造得很好。

在此处输入图像描述 But for some reason when I try to add this user to the roles table I am getting the following.但是由于某种原因,当我尝试将此用户添加到角色表时,我得到以下信息。

The Task is cancelled at Microsoft.AspNetCore.Identity.UserManager`1.d__116.MoveNext() at Web.SampleData.d__2.MoveNext() in SampleData.cs:line 118任务在 Microsoft.AspNetCore.Identity.UserManager`1.d__116.MoveNext() 处被取消,在 SampleData.cs:line 118 中 Web.SampleData.d__2.MoveNext()

I am using the code to add to the role manager the user我正在使用代码将用户添加到角色管理器

public static async Task<IdentityResult> 
           AssignRoles(IServiceProvider services, 
           string email, string[] roles)
{
  IdentityResult result = new IdentityResult();
  UserManager<ApplicationUser> _userManager = 
    services.GetService<UserManager<ApplicationUser>>();
   ApplicationUser user = await 
         _userManager.FindByEmailAsync(email);
   result = await _userManager.AddToRolesAsync(user, roles);            
   return result;
}

The role is being passed as "Parent" and the correct email address of ParentOne@Test.com so why am I getting a task is canceled?该角色作为“父级”传递,并且 ParentOne@Test.com 的正确 email 地址为什么我会取消任务?

As you see the above user has not been added to the aspnetuseroles table如您所见,上述用户尚未添加到 aspnetuseroles 表中

在此处输入图像描述

This is the complete seeding method这是完整的播种方法

public static void CreateParent(IServiceProvider 
                                serviceProvider)
{
    var context = new DBContext();// 
     serviceProvider.GetService<DBContext>();
      string[] roles = new string[] { "Parent" };
      foreach (string role in roles)
      {
        var roleStore = new RoleStore<IdentityRole>(context);
        if (!context.Roles.Any(r => r.Name == role))
           {
             roleStore.CreateAsync(new IdentityRole(role));
            }
        }
        
        var user = new ApplicationUser
        {
            FirstName = "Parent",
            LastName = "One",
            Email = "parentone@apps-Test.com",
            NormalizedEmail = "parentone@apps-Test.com",
            UserName = "parentone@apps-Test.com",
            NormalizedUserName = "parentone@apps-Test.com",
            PhoneNumber = "+111111111111",
            EmailConfirmed = true,
            PhoneNumberConfirmed = true,
            SecurityStamp = Guid.NewGuid().ToString("D")
        };

        var db = new DBContext();
        if (!db.Users.Any(u => u.UserName == user.UserName))
        {
            var password = new PasswordHasher<ApplicationUser>);
            var hashed = password.HashPassword(user,2 
                          Test12345!");
            user.PasswordHash = hashed;
            var userStore = new UserStore<ApplicationUser> 
            (context);
            var result = userStore.CreateAsync(user);

        }

        AssignRoles(serviceProvider, user.Email, roles);
        db.SaveChangesAsync();
    }

I call it from my web app startup.cs as such我从我的 web 应用程序 startup.cs 中调用它

public void Configure(IApplicationBuilder app, 
   IWebHostEnvironment env,IServiceProvider service)
{
        SampleData.CreateParent(service);

}

The reason why it is getting Cancelled is that you have an asynchronous call that you haven't actually added await to them.它被 Canceled 的原因是您有一个异步调用,但实际上并没有将 await 添加到它们。

You have async methods in your CreateParent function so you need to set it as您的 CreateParent function 中有异步方法,因此您需要将其设置为

public async Task CreateParent()

and you need to add await on你需要添加等待

await roleStore.CreateAsync(new IdentityRole(role));
await db.SaveChangesAsync();

public async Task Configure(IApplicationBuilder app, 
   IWebHostEnvironment env,IServiceProvider service)
{
        await SampleData.CreateParent(service);
}

I suggest you add it in the Program.cs我建议你在 Program.cs 中添加它

public class Program
    {
        public static async Task Main(string[] args)
        {
            new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile("appsettings.Development.json", optional: true, reloadOnChange: true)
                    .AddEnvironmentVariables()
                    .Build();

            var host = await CreateHostBuilder(args).Build().MigrateAndSeedDataAsync();

            await host.RunAsync();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                }).UseDefaultServiceProvider(options => options.ValidateScopes = false);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM