没有类型“Microsoft.AspNetCore.Identity.UserManager”的服务:尝试扩展IdentityUser时?

rsl1atfo  于 11个月前  发布在  .NET
关注(0)|答案(4)|浏览(168)

我在Mac机器上使用asp.net核心,我试图为我的ASP.NET mvc web应用程序创建一个自定义的ApplicationUser,它与基本的IdentityUser配合得很好。
尽管遵循Microsoft的此指南:
https://learn.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]”的服务。"}
以下是我的代码片段:

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<IdentityUser, IdentityRole>()应用程序打开,但注册当然不能正常工作。

zte4gxcn

zte4gxcn1#

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

axzmvihb

axzmvihb2#

核心2也有同样的问题。
您需要检查的另一个区域是中的_ManageNav.cshtml文件,在那里您必须使用@inject SignInManager<YOURCUSTOMMODEL> SignInManager更新@inject SignInManager<IdentityUser> SignInManager行。
希望有帮助

4dbbbstv

4dbbbstv3#

在dotnet核心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();

}


Update _LoginPartial.cshtml(shared --> view)

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

ukdjmx9f

ukdjmx9f4#

在ASP.NET 7或8中,
打开**_布局.cshtml**
和改变

@inject SignInManager<IdentityUser> SignInManager

字符串

@inject SignInManager<User> SignInManager


注:用户为客户机型用户名,替换为您的机型名称
打开**_ViewImports.cshtml**
and import导入model模型like this

@using Shop.Models.Accounts

相关问题