我在mac机上使用asp.net核心,我试图为我的asp.net mvc Web应用程序创建一个自定义ApplicationUser,它与基本IdentityUser可以很好地配合使用。
尽管遵循了Microsoft的本指南:
我遇到此错误:
{“错误”:“类型无服务 '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);
}
}
我只能从Microsoft官方指南中学到的唯一部分是编辑Account / Manage / Index.cshtml,因为在执行CLI步骤时文件没有被支撑!
请注意,当我在 startup.cs 中用IdentityUser替换ApplicationUser时,如下所示:
services.AddIdentity<IdentityUser, IdentityRole>()
应用程序打开,但是当然注册不能按预期正常工作。
答案 0 :(得分: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
答案 1 :(得分: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 :(得分:0)
核心2存在相同的问题。
需要检查的另一个区域是文件_ManageNav.cshtml,在那里您必须用@inject SignInManager<IdentityUser> SignInManager
更新行@inject SignInManager<YOURCUSTOMMODEL> SignInManager
。
希望有帮助