我正在制作我的第一个 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);
}
}
case sensitivity
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 表中的角色的确切大小写相匹配。如果错误仍然存在,请仔细检查您的数据库,以确保角色存在且大小写正确,并且数据库上下文不存在可能导致表被删除的问题。