首页 > 解决方案 > .ASP NET Core Identity - 无法解析“WebApp.Areas.Identity.Pages.Account.LoginModel”类型的服务

问题描述

我正在尝试使用 Microsoft 提供的教程测试和设置基本身份登录页面: https ://docs.microsoft.com/pl-pl/aspnet/core/security/authentication/identity?view=aspnetcore-5.0&tabs =visual-studio 我已经按照这些步骤,代码是自动生成的。为了测试它,我尝试运行它。主页打开正常。当我导航到登录页面 /Areas/Identity/Pages/Account/Login 时,我收到以下错误消息:

InvalidOperationException:尝试激活“WebApp.Areas.Identity.Pages.Account.LoginModel”时,无法解析“Microsoft.AspNetCore.Identity.SignInManager`1[WebApp.Areas.Identity.Data.WebAppUser]”类型的服务。

我注意到了类似的问题并按照其中一个步骤进行操作: 尝试激活“AuthController”时无法解析类型“Microsoft.AspNetCore.Identity.UserManager”的服务 我尝试修改 Startup.cs 文件,如下所示:

services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
        .AddEntityFrameworkStores<ApplicationDbContext>();

虽然没有解决问题。我附在当前配置下方:

启动.cs

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.EntityFrameworkCore;
using WebApp.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using WebApp.Areas.Identity.Pages.Account;

namespace WebApp
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                   Configuration.GetConnectionString("DefaultConnection")));
            services.AddDatabaseDeveloperPageExceptionFilter();
            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
            }
            else
            {
                app.UseExceptionHandler("/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 =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

登录.cshtml.cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using WebApp.Areas.Identity.Data;

namespace WebApp.Areas.Identity.Pages.Account
{
    [AllowAnonymous]
    public class LoginModel : PageModel
    {
        private readonly UserManager<WebAppUser> _userManager;
        private readonly SignInManager<WebAppUser> _signInManager;
        private readonly ILogger<LoginModel> _logger;

        public LoginModel(SignInManager<WebAppUser> signInManager, 
            ILogger<LoginModel> logger,
            UserManager<WebAppUser> userManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
        }

        [BindProperty]
        public InputModel Input { get; set; }

        public IList<AuthenticationScheme> ExternalLogins { get; set; }

        public string ReturnUrl { get; set; }

        [TempData]
        public string ErrorMessage { get; set; }

        public class InputModel
        {
            [Required]
            [EmailAddress]
            public string Email { get; set; }

            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }

            [Display(Name = "Remember me?")]
            public bool RememberMe { get; set; }
        }

        public async Task OnGetAsync(string returnUrl = null)
        {
            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                ModelState.AddModelError(string.Empty, ErrorMessage);
            }

            returnUrl ??= Url.Content("~/");

            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            ReturnUrl = returnUrl;
        }

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
        
            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return LocalRedirect(returnUrl);
                }
                if (result.RequiresTwoFactor)
                {
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToPage("./Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return Page();
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }
    }
}

标签: c#asp.net-corerazorasp.net-identityrazor-pages

解决方案


如果您在创建和实现自定义用户模型之前搭建 Identity ,您将不得不再次搭建 Identity(覆盖您以前的页面)或手动替换 Identity 页面中每个提及 IdentityUser 的自定义用户模型。

您的自定义用户模型还需要在以下某些文件中提及:ApplicationDbContext.cs:这将是必需的。例如:

public class ApplicationDbContext : IdentityDbContext<CustomUser>

Startup.cs:这将是必需的。例如:

services.AddDefaultIdentity<CustomUser>(options => options.SignIn.RequireConfirmedAccount = false)

Program.cs:可选,如果你从这里调用你的应用程序方法,你会想要传递 UserManager 服务,这需要定制的用户模型。例如:

var userManager = serviceProvider.GetRequiredService<UserManager<CustomUser>>();

_LoginPartial.cshtml:可选,如果您需要检查用户是否登录以及使用哪个角色。例如:

@inject SignInManager<CustomUser> SignInManager
@inject UserManager<CustomUser> UserManager

推荐阅读