【问题标题】:No service for type 'Microsoft.AspNetCore.Identity.UserManager' : while trying to extend IdentityUser?'Microsoft.AspNetCore.Identity.UserManager' 类型没有服务:尝试扩展 IdentityUser?
【发布时间】:2019-01-11 17:34:02
【问题描述】:

我在 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]' 已注册。"}

这是我的代码的 sn-ps:

startup.cs

    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));
        });
    }

ApplicationUser.cs

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

Register.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();
    }

ApplicationDbContext

    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 中将 ApplicationUser 替换为 IdentityUser 时,如下所示: services.AddIdentity&lt;IdentityUser, IdentityRole&gt;() 应用程序打开,但当然注册不能按预期正常工作。

【问题讨论】:

  • 也许你在其他地方注入非泛型UserManager
  • 我之前已经偶然发现了那个,它没有任何效果。无论如何,它是在 2016 年; asp.net 核心发生了很多变化
  • 尝试搜索IdentityUserEntire Solution,你会找到任何IdentityUser吗? the file was not scaffolded 的步骤是什么?您在搭建脚手架时是否遇到任何错误?尝试与我们分享您的演示项目。
  • 非常感谢您的帮助...无论如何,在意识到这些只是我们遇到的怪癖之后,我意识到我必须一劳永逸地放弃 asp core。这会浪费很多开发时间。我希望允许保留这个问题,以便一旦找到解决方案,它可以帮助其他开发人员。除非希望 asp core 较新的迭代摆脱这些怪癖,否则这个主题将不再相关,我将其删除。

标签: c# asp.net asp.net-core


【解决方案1】:

问题出在'_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

【讨论】:

  • 我不敢相信这是我的解决方案,经过数小时的搜索,非常感谢!
【解决方案2】:

在 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 ConfigureServices

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

【讨论】:

  • msdocs 的链接说要求是 .net core 2.2 或更高版本,您的解决方案将不起作用。 @Olawale 回答明白了
【解决方案3】:

与核心 2 有同样的问题。

您需要检查的另一个区域是文件 _ManageNav.cshtml,您必须在其中将 @inject SignInManager&lt;IdentityUser&gt; SignInManager 行更新为 @inject SignInManager&lt;YOURCUSTOMMODEL&gt; SignInManager

希望有帮助

【讨论】:

  • 谢谢你,这是我的错,你为我节省了几个小时
猜你喜欢
  • 1970-01-01
  • 2019-05-20
  • 1970-01-01
  • 2021-08-07
  • 2022-01-04
  • 1970-01-01
  • 1970-01-01
  • 2019-03-05
  • 2021-11-01
相关资源
最近更新 更多