当我尝试更改剃刀中的角色时,它会删除整个数据库

问题描述 投票:0回答:1

我正在制作我的第一个 C# 网站,我想制作包含所有用户的管理页面(我使用 Blazor 个人帐户 UI),并在它们旁边有 3 个按钮。言归正传,其中一个按钮应该将用户角色更改为管理员,但每当我单击它时,它都会删除我的 dbo.AspNetUserRole 数据库。同样在控制台中我收到此错误:

fail: Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost[111]
      Unhandled exception in circuit 'e6xqofkz95KS-EPToEuPmnxEa0a898ru3oSC6UrZRXk'.
      System.InvalidOperationException: Role ADMIN does not exist.
         at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.AddToRoleAsync(TUser user, String normalizedRoleName, CancellationToken cancellationToken)
         at Microsoft.AspNetCore.Identity.UserManager`1.AddToRoleAsync(TUser user, String role)
         at whoisalmo.cz.Components.Pages.AdminPanel.ChangeToAdmin(ApplicationUser user) in C:\Users\steam\Source\Repos\AlmoAsdwak\whoisalmo.cz\Components\Pages\AdminPanel.razor:line 84
         at whoisalmo.cz.Components.Pages.AdminPanel.<>c__DisplayClass0_0.<<BuildRenderTree>b__4>d.MoveNext() in C:\Users\steam\Source\Repos\AlmoAsdwak\whoisalmo.cz\Components\Pages\AdminPanel.razor:line 32
      --- End of stack trace from previous location ---
         at Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(Task task)
         at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
据我所知,其中指出角色 Admin 丢失,但在 dbo.AspNetRoles 中列出:“cbee81c7-44e5-4106-8ecc-b8294601de87 Admin ADMIN NULL”现在我没有主意了。 右下方是主要的 AdminPanel.razor 之前感谢您发送给我的所有想法

@page "/admin" @page "/adminpanel" @rendermode InteractiveServer @using Microsoft.AspNetCore.Authorization @using System.ComponentModel.DataAnnotations @using Microsoft.AspNetCore.Authentication @using Microsoft.AspNetCore.Identity @using Microsoft.EntityFrameworkCore @using whoisalmo.cz.Data @inject SignInManager<ApplicationUser> SignInManager @inject NavigationManager manager @inject RoleManager<IdentityRole> RoleManager <AuthorizeView Roles="HeadAdmin,Admin"> <Authorized> <h1 style="text-align:center">Hello Admin</h1> <p> <button type="submit" name="generateToken" @onclick="UpdateToken" class="w-100 btn btn-lg btn-primary">Update Token</button> </p> <p style="text-align:center"> <label style="text-align:center">@token</label> <hr /> <h1>Users</h1> @foreach (var user in Users) { if (user.Email == "[email protected]") { //continue; } <div> <label>User: @user.Email</label> <button type="button" @onclick="() => ProgramFurther(user)" class="btn btn-sm btn-secondary">Do something??</button> <button type="button" @onclick="async () => await ChangeToAdmin(user)" class="btn btn-sm btn-secondary">Change rights to: Admin</button> <button type="button" @onclick="() => Remove(user)" class="btn btn-sm btn-secondary">Remove User</button> </div> <br /> } </p> </Authorized> <NotAuthorized> <p>@context.User.IsInRole("HeadAdmin")</p> <p>@context.User.Identity.Name</p> </NotAuthorized> </AuthorizeView> @code { private string token = "Not changed yet"; List<ApplicationUser> Users=null; List<IdentityRole> Roles = null; protected override void OnParametersSet() { Users = SignInManager.UserManager.Users.AsNoTracking().ToList(); Roles = RoleManager.Roles.AsNoTracking().ToList(); base.OnParametersSet(); } private async Task Remove(ApplicationUser user) { await SignInManager.UserManager.DeleteAsync(user); manager.NavigateTo(manager.Uri, true); } private async void ProgramFurther(ApplicationUser user) { } private async Task ChangeToAdmin(ApplicationUser user) { try { await SignInManager.UserManager.RemoveFromRoleAsync(user, "Member"); } catch (Exception ex) { Console.WriteLine(ex); } await SignInManager.UserManager.AddToRoleAsync(user, "Admin"); } private void UpdateToken() { Random random = new Random(); const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; string tmp = new string(Enumerable.Repeat(chars, 32).Select(s => s[random.Next(s.Length)]).ToArray()); token = tmp; if (!File.Exists("token.secret")) { File.Create("token.secret").Close(); } File.WriteAllText("token.secret", tmp); } }


    我尝试过观看此视频
  1. YouTube,但几乎在最后,当他开始输入“If(User.IsInRole(...))”(18:48)时,我无法继续下去,因为找不到用户函数我是我的代码。
  2. 我尝试过很多事情,例如将按钮作为会员和管理员之间的杠杆,但这都不起作用。
我希望它将用户角色切换为管理员,如果会员和管理员之间发生冲突,那就更好了

c# button razor blazor roles
1个回答
0
投票
您遇到的错误可能是由于角色名称的

case sensitivity

 问题造成的。在您的代码中,您尝试将用户添加到“Admin”角色,该角色必须与数据库中的名称完全匹配。 ASP.NET Core Identity 角色名称区分大小写。

private async Task ChangeToAdmin(ApplicationUser user) { // Check if the "Admin" role exists var adminRoleExists = await RoleManager.RoleExistsAsync("Admin"); if (!adminRoleExists) { // Handle the case where the Admin role doesn't exist // You could create the role here if necessary Console.WriteLine("The Admin role does not exist."); return; } // Remove the user from the "Member" role, if they are in it var isInMemberRole = await SignInManager.UserManager.IsInRoleAsync(user, "Member"); if (isInMemberRole) { var removeRoleResult = await SignInManager.UserManager.RemoveFromRoleAsync(user, "Member"); if (!removeRoleResult.Succeeded) { // Handle the error, e.g., log it or display a message Console.WriteLine("Failed to remove user from the Member role."); return; } } // Add the user to the "Admin" role var addToRoleResult = await SignInManager.UserManager.AddToRoleAsync(user, "Admin"); if (!addToRoleResult.Succeeded) { // Handle the error, e.g., log it or display a message Console.WriteLine("Failed to add user to the Admin role."); return; } }
请记住与存储在 dbo.AspNetRoles 表中的角色的确切大小写相匹配。如果错误仍然存在,请仔细检查您的数据库,以确保角色存在且大小写正确,并且数据库上下文不存在可能导致表被删除的问题。

© www.soinside.com 2019 - 2024. All rights reserved.