[英]Unable to resolve service for type 'Microsoft.AspNetCore.Identity.SignInManager` while attempting to activate 'xxxxx.LoginModel'
[英].ASP NET Core Identity - Unable to resolve service for type '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();
}
}
}
如果您在創建和實現自定義用戶模型之前搭建 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.