nik*_*ovn 9 c# asp.net-web-api asp.net-identity asp.net-core-mvc asp.net-core
我有一个较旧的asp.net核心身份数据库,我想将一个新项目(一个web api)映射到它.
仅仅为了测试,我复制了Models文件夹,以及上一个项目中的ApplicationUser文件(ApplicationUser只是继承自IdentityUser,没有任何变化) - 首先执行DB似乎是一个坏主意.
我在ConfigureServices中注册了Identity(但我没有将它添加到管道中,因为我的唯一目的是使用UserStore)
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)
我的期望是现在
UserManager<ApplicationUser>
Run Code Online (Sandbox Code Playgroud)
...应该自动注入构造函数.
但是,将以下代码添加到控制器私有UserManager _userManager时;
public UserController(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
Run Code Online (Sandbox Code Playgroud)
...每次调用api都会以异常结束:HttpRequestException:响应状态代码不表示成功:500(内部服务器错误).
删除"注入"代码可以顺利运行可以接受请求的web api.
在我的任何代码到达之前发生这种情况很难调试.知道为什么会这样吗?
PS从异常设置窗口启用所有异常后我得到了这个:
抛出异常:
Microsoft.Extensions.DependencyInjection.dll中的"System.InvalidOperationException"附加信息:尝试激活'Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`4 [Namespace.Models]时,无法解析类型'Namespace.Data.ApplicationDbContext'的服务.ApplicationUser,Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole,Namespace.Data.ApplicationDbContext,System.String]".
你有app.UseIdentity();这个Configure方法的电话:
public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
/*...*/
app.UseIdentity();
/*...*/
}
Run Code Online (Sandbox Code Playgroud)
编辑
你还有这条services.AddIdentity<ApplicationUser, IdentityRole>()线吗?
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
Run Code Online (Sandbox Code Playgroud)
这应该工作正常.还请检查是否ApplicationDbContext继承自IdentityDbContext.
DI 容器无法解析依赖项。将其添加到服务集合
services.AddTransient<UserManager<ApplicationUser>>();
services.AddTransient<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)
您还应该熟悉官方文档
| 归档时间: |
|
| 查看次数: |
24047 次 |
| 最近记录: |