簡體   English   中英

沒有類型“Microsoft.AspNetCore.Identity.UserManager”的服務:在嘗試擴展 IdentityUser 時?

[英]No service for type 'Microsoft.AspNetCore.Identity.UserManager' : while trying to extend IdentityUser?

我在 mac 機器上使用 asp.net 核心,我試圖為我的 asp.net mvc web 應用程序創建一個自定義 ApplicationUser,它與基本 IdentityUser 一起工作得非常好。

盡管遵循 Microsoft 的本指南:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/add-user-data?view=aspnetcore-2.1&tabs=visual-studio

我面臨這個錯誤:

{"error":"沒有注冊'Microsoft.AspNetCore.Identity.UserManager`1[Microsoft.AspNetCore.Identity.IdentityUser]'類型的服務。"}

以下是我的代碼片段:

啟動文件

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {

        // [...]

        services.AddDbContext<ApplicationDbContext>(
            options => options.UseSqlServer(identityDbContextConnection));
        // Relevant part: influences the error
        services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();


        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });
    }

應用程序用戶.cs

    // Add profile data for application users by adding properties to the ApplicationUser class
public class ApplicationUser : IdentityUser
{
    [Required]
    public string DrivingLicense { get; set; }
}

注冊.cshtml.cs

public class RegisterModel : PageModel
{
    private readonly SignInManager<ApplicationUser> _signInManager;
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly ILogger<RegisterModel> _logger;
    private readonly IServiceProvider _services;

    public RegisterModel(
        UserManager<ApplicationUser> userManager,
        SignInManager<ApplicationUser> signInManager,
        ILogger<RegisterModel> logger,
        IServiceProvider services
    )
    {
        _userManager = userManager;
        _signInManager = signInManager;
        _logger = logger;
        _services = services;
    }

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

    public string ReturnUrl { get; set; }

    public class InputModel
    {
        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        // Added for ApplicationUser
        [Required]
        [Display(Name = "Driving License")]
        public string DrivingLicense { get; set; }
        // -----------------------------
        // [...]
    }

    public void OnGet(string returnUrl = null)
    {
        ReturnUrl = returnUrl;
    }

    public async Task<IActionResult> OnPostAsync(string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser { 
                UserName = Input.Email, 
                Email = Input.Email, 
                DrivingLicense = Input.DrivingLicense // property added by ApplicationUser
            };
            var result = await _userManager.CreateAsync(user, Input.Password);
            if (result.Succeeded)
            {

                _logger.LogInformation("User created a new account with password.");

                await _signInManager.SignInAsync(user, isPersistent: false);
                return LocalRedirect(returnUrl);
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }
        }

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

來自Manage/Index.cshtml.cs 的片段

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

        // Added for ApplicationUser
        [Required]
        [Display(Name = "Driving License")]
        public string DrivingLicense { get; set; }
        // -----------------------------

        [Phone]
        [Display(Name = "Phone number")]
        public string PhoneNumber { get; set; }
    }



public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        // [...]

        // Added for ApplicationUser
        if (Input.DrivingLicense != user.DrivingLicense)
        {
            user.DrivingLicense = Input.DrivingLicense;
        }
        await _userManager.UpdateAsync(user);
        // -------------------------

        await _signInManager.RefreshSignInAsync(user);
        StatusMessage = "Your profile has been updated";
        return RedirectToPage();
    }

應用程序數據庫上下文

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
    }
}

我無法從官方微軟指南中遵循的唯一部分是編輯 Account/Manage/Index.cshtml,因為在我執行 CLI 步驟時該文件沒有搭建!

請注意,當我在startup.cs中用 IdentityUser 替換 ApplicationUser 時,如下所示: services.AddIdentity<IdentityUser, IdentityRole>()應用程序打開但當然注冊無法按預期正常工作。

問題出在“_LoginPartial.cshtml”中

刪除這個

@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager

添加這個

@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

在 dotnet core 2.1 中我遇到了同樣的問題,以下步驟解決了我的問題

1 ) 擴展 IdentityUser 或 IdentityRole

public class ApplicationUser : IdentityUser<Guid>
{
    public DateTime JoinTime { get; set; } = DateTime.Now;
    public DateTime DOB { get; set; } = Convert.ToDateTime("01-Jan-1900");
}
public class ApplicationRole : IdentityRole<Guid>
{
    public string Description { get; set; }
}

2)更新ApplicationDbContext類

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, Guid>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
    {

    }
}

3) 更新 Stratup.cs 配置服務

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, AppClaimsPrincipalFactory>();


    services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, ApplicationRole>().AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultUI()
        .AddDefaultTokenProviders();

}

更新 _LoginPartial.cshtml(共享 --> 查看)

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

核心2有同樣的問題。

您需要檢查的另一個區域是 _ManageNav.cshtml 文件,在那里您必須使用@inject SignInManager<YOURCUSTOMMODEL> SignInManager更新行@inject SignInManager<IdentityUser> SignInManager @inject SignInManager<YOURCUSTOMMODEL> SignInManager

希望有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM