.net 无效操作异常:角色ADMIN不存在

hrirmatl  于 2023-03-13  发布在  .NET
关注(0)|答案(2)|浏览(215)

我正尝试使用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
            {

这是程序. 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; }

    }
}
wtzytmuj

wtzytmuj1#

根据问题描述,角色表中缺少“admin”角色。
在代码await _userManager.AddToRoleAsync(user, "Admin");之前,您需要添加业务逻辑,如@klekmek所评论的,编写代码以检查表中是否有Admin角色,代码片段来自this high vote answer

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");
eoxn13cs

eoxn13cs2#

好的!我在Tiny Wanganswer的帮助下找到了一个解决方案,这个问题的解决方案是在Roles表中添加NormalizedName(大写字母)而不是NULL!您可以手动执行此操作,也可以使用Tiny Wang的上述代码

相关问题