【问题标题】:InvalidOperationException: Role ADMIN does not existInvalidOperationException:角色 ADMIN 不存在
【发布时间】:2022-01-02 20:24:51
【问题描述】:

我正在尝试构建一个带有角色的注册系统,以查看我的数据有限制 使用 Identity 的 Asp.Net 核心项目,所以我收到了这个错误,如果有人指导我解决问题,我将不胜感激.......................... ..

InvalidOperationException: Role ADMIN does not exist.
Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore<TUser, TRole, TContext, TKey, TUserClaim, TUserRole, TUserLogin, TUserToken, TRoleClaim>.AddToRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken)
Microsoft.AspNetCore.Identity.UserManager<TUser>.AddToRoleAsync(TUser user, string role)
Relog.Controllers.AccountController.Register(AppUser model) in AccountController.cs
-
                    Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password );
                if(result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "Admin");
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {

这是 Program.cs

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Relog.Data;
using Relog.Models;
//using System.Configuration;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<AppUserDbContext>(options =>
    options.UseSqlServer(connectionString));
//builder.Services.AddDbContext<StockDbContext>(options =>
//    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<AppUserDbContext>();
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddDbContext<AppUserDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
//builder.Services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{


    app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");
    endpoints.MapRazorPages();

});

app.Run();

这是帐户控制器

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Relog.Models;
using System.Linq;
using System.Threading.Tasks;

namespace Relog.Controllers
{
    public class AccountController : Controller
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;

        public AccountController(UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;

        }



        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public async Task  <IActionResult> Register(AppUser model)
        {
            if(ModelState.IsValid)
            {
                var user = new IdentityUser
                {
                    UserName = model.FirstName + model.LastName,
                    Email = model.Email
                };

                var result = await _userManager.CreateAsync(user, model.Password );
                if(result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "Admin");
                    return RedirectToAction("Index", "Home");

                }
            }
            else
            {
                ModelState.AddModelError("", "Invalid Register!");
                return View(model);
            }

            return View("Register", model);

        }
    }
}

这是我的 Dbcontext 文件

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Relog.Models;


namespace Relog.Data
{
    public class AppUserDbContext : IdentityDbContext
    {
        public AppUserDbContext(DbContextOptions<AppUserDbContext> options) : base(options)
        {

        }


        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity<IdentityUser>();
        }


        public DbSet<Relog.Models.AppUser> AppUsers { get; set; }

    }
}

我的模型:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Relog.Models
{
    public class AppUser
    {

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }

        [Required]
        [Column(TypeName = "varchar(150)")]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }


        [Required]
        [Column(TypeName = "varchar(150)")]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }



        [Required(ErrorMessage = "Email is required")]
        [EmailAddress]
        public string Email { get; set; }



        [Required(ErrorMessage = "Password is required")]
        [DataType(DataType.Password)]
        public string Password { get; set; }



        [DataType(DataType.Password)]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

    }
}

【问题讨论】:

标签: c# .net asp.net-mvc asp.net-core asp.net-web-api


【解决方案1】:

根据问题描述,角色表中缺少“admin”角色。

await _userManager.AddToRoleAsync(user, "Admin");这行代码之前,你需要添加业务逻辑,就像@klekmek评论的那样,编写代码来检查表中是否有Admin角色,代码来自this high vote answer的sn-p。

var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var roleExist = await RoleManager.RoleExistsAsync("Admin");
if (!roleExist)
{
    roleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
}
await _userManager.AddToRoleAsync(user, "Admin");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2015-01-23
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    相关资源
    最近更新 更多