C# 我犯了这个错误;无法解析AspNetCore.Identity.SignInManager类型的服务;当我使用ApplicationUser而不是IdentityUser时
我有一个.NET Core 3.1 Web Api,我创建了一个从IdentityUser继承的ApplicationUser类,因为我需要注册一些其他属性。但当我尝试注册一个新用户时,会出现以下错误: 尝试激活“MyProject.Api.Controllers.AuthController”时,无法解析类型为“Microsoft.AspNetCore.Identity.SignInManager[MyProject.Api.ApplicationUser]”的服务 下面是在启动类上设置依赖项的IdentityConfig类:C# 我犯了这个错误;无法解析AspNetCore.Identity.SignInManager类型的服务;当我使用ApplicationUser而不是IdentityUser时,c#,.net,entity-framework-core,asp.net-identity,identity,C#,.net,Entity Framework Core,Asp.net Identity,Identity,我有一个.NET Core 3.1 Web Api,我创建了一个从IdentityUser继承的ApplicationUser类,因为我需要注册一些其他属性。但当我尝试注册一个新用户时,会出现以下错误: 尝试激活“MyProject.Api.Controllers.AuthController”时,无法解析类型为“Microsoft.AspNetCore.Identity.SignInManager[MyProject.Api.ApplicationUser]”的服务 下面是在启动类上设置依赖项
public static class IdentityConfig
{
public static IServiceCollection AddIdentityConfig(this IServiceCollection services,
IConfiguration configuration)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddErrorDescriber<IdentityMensagensPortugues>()
.AddDefaultTokenProviders();
var appSettingsSection = configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x =>
{
x.RequireHttpsMetadata = true;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = appSettings.ValidoEm,
ValidIssuer = appSettings.Emissor
};
});
return services;
}
}
公共静态类标识配置
{
公共静态iSeries收集附加身份配置(此iSeries收集服务,
i配置(配置)
{
services.AddDbContext(选项=>
options.UseSqlServer(configuration.GetConnectionString(“DefaultConnection”));
services.AddDefaultIdentity()
.AddRoles()
.AddEntityFrameworkStores()
.AddErrorDescriber()
.AddDefaultTokenProviders();
var appsetingssection=configuration.GetSection(“AppSettings”);
services.Configure(应用设置部分);
var appSettings=appSettingsSection.Get();
var key=Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x=>
{
x、 DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
x、 DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(x=>
{
x、 RequireHttpsMetadata=true;
x、 SaveToken=true;
x、 TokenValidationParameters=新的TokenValidationParameters
{
ValidateSuersigningKey=true,
IssuerSigningKey=新对称性安全密钥(密钥),
validateisuer=true,
ValidateAudience=true,
validudience=appSettings.ValidoEm,
ValidisUser=appSettings.Emissor
};
});
返回服务;
}
}
下面是ApplicationDbContext类:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { }
}
public类ApplicationDbContext:IdentityDbContext{
公共应用程序DBContext(DbContextOptions选项):基本(选项){}
}
以下是控制器类:
public class AuthController : MainController
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly UserManager<ApplicationUser> _userManager;
private readonly AppSettings _appSettings;
private readonly ILogger _logger;
public AuthController(INotificator notificator,
SignInManager<ApplicationUser> signInManager,
UserManager<ApplicationUser> userManager,
IOptions<AppSettings> appSettings,
IUser user, ILogger<AuthController> logger) : base(notificator, user)
{
_signInManager = signInManager;
_userManager = userManager;
_logger = logger;
_appSettings = appSettings.Value;
}
[HttpPost("new-account")]
public async Task<ActionResult> Register(RegisterUserViewModel registerUser)
{
if (!ModelState.IsValid) return CustomResponse(ModelState);
ApplicationUser user = new ApplicationUser {
UserName = registerUser.Email,
Email = registerUser.Email,
Cpf = registerUser.Cpf,
ZipCode = registerUser.ZipCode,
Gender = registerUser.Gender,
EmailConfirmed = true
};
var result = await _userManager.CreateAsync(user, registerUser.Password);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, false);
return CustomResponse(await GerarJwt(user.Email));
}
foreach (var error in result.Errors)
{
NotifyError(error.Description);
}
return CustomResponse(registerUser);
}
[HttpPost("enter")]
public async Task<ActionResult> Login(LoginUserViewModel loginUser)
{
if (!ModelState.IsValid) return CustomResponse(ModelState);
var result = await _signInManager.PasswordSignInAsync(loginUser.Email, loginUser.Password, false, true);
if (result.Succeeded)
{
_logger.LogInformation("User "+ loginUser.Email +" successfully logged in");
return CustomResponse(await GerarJwt(loginUser.Email));
}
if (result.IsLockedOut)
{
NotifyError("User temporarily blocked by invalid attempts");
return CustomResponse(loginUser);
}
NotificarErro("User or Password incorrect");
return CustomResponse(loginUser);
}
}
public类AuthController:MainController
{
专用只读签名管理器\u签名管理器;
私有只读用户管理器_UserManager;
私有只读应用设置\u应用设置;
专用只读ILogger\u记录器;
公共授权控制器(INotificator notificator,
SignInManager SignInManager,
用户管理器用户管理器,
IOPS应用程序设置,
IUser用户,ILogger记录器):基本(通知者,用户)
{
_signInManager=signInManager;
_userManager=userManager;
_记录器=记录器;
_appSettings=appSettings.Value;
}
[HttpPost(“新账户”)]
公共异步任务寄存器(RegisterUserModel registerUser)
{
如果(!ModelState.IsValid)返回CustomResponse(ModelState);
ApplicationUser用户=新的ApplicationUser{
用户名=registerUser.Email,
Email=registerUser.Email,
Cpf=注册服务器.Cpf,
ZipCode=registerUser.ZipCode,
性别=注册用户性别,
emailconfirm=true
};
var result=await _userManager.CreateAsync(用户,registerUser.Password);
if(result.successed)
{
wait _signInManager.SignInAsync(用户,false);
返回CustomResponse(等待GerarJwt(user.Email));
}
foreach(result.Errors中的变量错误)
{
NotifyError(error.Description);
}
返回CustomResponse(registerUser);
}
[HttpPost(“输入”)]
公共异步任务登录(LoginUserViewModel loginUser)
{
如果(!ModelState.IsValid)返回CustomResponse(ModelState);
var result=wait _signInManager.PasswordSignInAsync(logiuser.Email,logiuser.Password,false,true);
if(result.successed)
{
_logger.LogInformation(“用户”+登录用户.Email+“成功登录”);
返回CustomResponse(等待GerarJwt(logiuser.Email));
}
如果(结果IsLockedOut)
{
NotifyError(“用户被无效尝试暂时阻止”);
返回CustomResponse(登录用户);
}
通知错误(“用户或密码不正确”);
返回CustomResponse(登录用户);
}
}
确保您的ApplicationDbContext具有ApplicationUser和IdentityRole,因为您已经在startup类中定义了这种方式
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string>
{
public ApplicationDbContext (DbContextOptions<ApplicationDbContext> options) : base(options)
{
}
}
public类ApplicationDbContext:IdentityDbContext
{
公共应用程序DBContext(DbContextOptions选项):基本(选项)
{
}
}
我无法准确指出要修复的位置,但我可以确定您正在尝试将SignInManager
注入控制器。建议在启动时的某个位置,管理器未向用户注册
如果您尝试注入
SignInManager
,它能工作吗?如果是这样的话,您只需要找到一种方法,用您的自定义用户配置DI。如果我尝试注入SignInManager
它就不起作用了。