如何在IdentityCore .NET 8中注册UserManager

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

我正在尝试使用个人帐户在 Blazor、.NET 8、服务器中进行用户管理。

我尝试为此创建一个用户页面,但出现错误:

InvalidOperationException:无法为类型“StoreManagement.Components.Pages.Users.Users”上的属性“_UserManager”提供值。没有类型为“Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]”的已注册服务。

Users.razor

@page "/users"

@using Microsoft.AspNetCore.Authorization;
@using Microsoft.AspNetCore.Identity;

@inject UserManager<IdentityUser> _UserManager
@inject RoleManager<IdentityRole> _RoleManager
@inject AuthenticationStateProvider AuthenticationStateProvider

<h3>Administration</h3>

<AuthorizeView>
    <Authorized>
        @if (@context.User.IsInRole(ADMINISTRATION_ROLE))
        {
            <p>You are in @ADMINISTRATION_ROLE </p>
        }
        else
        {
            <p>You're not signed in as a user in @ADMINISTRATION_ROLE.</p>
        }
    </Authorized>
    <NotAuthorized>
        <p>You're not loggged in.</p>
    </NotAuthorized>
</AuthorizeView>

@code {
    [CascadingParameter]
    private Task<AuthenticationState> authenticationStateTask { get; set; }
    string ADMINISTRATION_ROLE = "Admin";
    System.Security.Claims.ClaimsPrincipal CurrentUser;

    protected override async Task OnInitializedAsync()
    {
        var RoleResult = await _RoleManager.FindByNameAsync(ADMINISTRATION_ROLE);

        if (RoleResult == null)
        {
            await _RoleManager.CreateAsync(new IdentityRole(ADMINISTRATION_ROLE));
        }

        var user = await _UserManager.FindByEmailAsync("[email protected]");

        if (user != null)
        {
            var UserResult = await _UserManager.IsInRoleAsync(user, ADMINISTRATION_ROLE);

            if (!UserResult)
            {
                // Put admin in Administrator role
                await _UserManager.AddToRoleAsync(user, ADMINISTRATION_ROLE);
            }
        }

        CurrentUser = (await authenticationStateTask).User;
    }
}

Program.cs

using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using StoreManagement.Components;
using StoreManagement.Components.Account;
using StoreManagement.Data;
using StoreManagement.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped<IdentityUserAccessor>();
builder.Services.AddScoped<IdentityRedirectManager>();
builder.Services.AddScoped<AuthenticationStateProvider, IdentityRevalidatingAuthenticationStateProvider>();

builder.Services.AddAuthentication(options =>
    {
        options.DefaultScheme = IdentityConstants.ApplicationScheme;
        options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
    })
    .AddIdentityCookies();

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddSignInManager()
    .AddDefaultTokenProviders();

builder.Services.AddSingleton<IEmailSender<ApplicationUser>, EmailSender>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseMigrationsEndPoint();
}
else
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();
app.UseAntiforgery();

app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

// Add additional endpoints required by the Identity /Account Razor components.
app.MapAdditionalIdentityEndpoints();

app.Run();
asp.net-core .net-8.0
1个回答
0
投票

您可以在 AddIdentityCore 中注册 userManager 服务,如下所示:

builder.Services.AddIdentityCore<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddRoles<IdentityRole>()
    .AddUserManager<UserManager<ApplicationUser>>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddSignInManager()
    .AddDefaultTokenProviders();

如果您使用自定义

ApplicationUser
实体,则应将所有
IdentityUser
更改为
ApplicationUser
。另外你还需要注入使用
@inject UserManager<ApplicationUser> _UserManager

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