Dav*_*agi 9 c# .net-core asp.net-core
此错误的可能原因是:
InvalidOperationException:没有注册类型为'Microsoft.AspNetCore.Identity.UserManager [Microsoft.AspNetCore.Identity.IdentityUser]'的服务。
我的目标框架是netcoreapp2.1。
这是我的用户商店类:
public class MyUserStore : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
和我的用户角色类:
public class MyUserRole : IdentityRole
{
public string Description { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的DbContext:
public class ApplicationDbContext : IdentityDbContext<MyUserStore,MyUserRole,string>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options): base(options) { }
}
Run Code Online (Sandbox Code Playgroud)
我的ConfigureServices方法Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//services.AddDefaultIdentity<IdentityUser>()
// .AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentity<MyUserStore, MyUserRole>(cfg => {
cfg.User.RequireUniqueEmail = true;
}).AddEntityFrameworkStores<ApplicationDbContext>();
services.AddTransient<Seeder>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
Run Code Online (Sandbox Code Playgroud)
我想了解为什么会这样,什么是最佳实践。
小智 15
核心 2 有同样的问题。您需要检查的另一个区域是文件_ManageNav.cshtml. 尝试更新行
@inject SignInManager<IdentityUser> SignInManager
Run Code Online (Sandbox Code Playgroud)
和
@inject SignInManager<YOURCUSTOMMODEL> SignInManager
Run Code Online (Sandbox Code Playgroud)
MyUserStore为AspNetCore身份注册自己的名称(错误名称,应为MyUser)时,UserManager <>类型将注册为ServiceCollection UserManager<MyUserStore>。
每当您要解析时UserManager<>,将在启动时注册的身份用户模型指定为type参数。这将是UserManager<MyUserStore>在您的具体情况。
调用GetRequiredService<UserManager<IdentityUser>>()结果服务提供者时,GetRequiredService<UserManager<IdentityUser>>()将引发上述异常。
这通常发生在剃刀视图中。例如。
@inject Microsoft.AspNetCore.Identity.UserManager<Microsoft.AspNetCore.Identity.IdentityUser> userManager
Run Code Online (Sandbox Code Playgroud)
同样,在其他类中自己调用它时,就像在Seeder服务中一样。或其他代码部分。异常的调用堆栈应该给您提示发生情况的地方。
这是解决方案,在中_LoginPartial.cshtml,替换
@using Microsoft.AspNetCore.Identity
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
Run Code Online (Sandbox Code Playgroud)
与
@using Microsoft.AspNetCore.Identity
@inject SignInManager<MyUserStore> SignInManager
@inject UserManager<MyUserStore> UserManager
Run Code Online (Sandbox Code Playgroud)
注意区别,IdentityUser与MyUserStore
| 归档时间: |
|
| 查看次数: |
6715 次 |
| 最近记录: |