我已经在Identity
中实现了Asp.Net.Core MVC 3
,因为我们已经有了要使用的数据库表。在调用下面的方法时,我得到了错误,它们都在同一方法的UserManager
中调用。在查看此方法的源代码时,这是因为Store变量为null。但是我不太确定如何确保它不为空。我在网上查看了各种解决方案,但没有一个能解决我的问题。
我的解决方案正在使用SignInManager
输入密码,但是我无法通过它来传递“角色”错误。
ConfigureServices 方法
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
options.Filters.Add(new AuthorizeFilter(policy));
options.EnableEndpointRouting = false;
});
services.AddDbContext<EntitiesModel>(options => options.UseSqlServer(
Configuration["Data:ConnectionStrings:XXXXXXXXXXXXX"]));
services.AddIdentity<UserViewModel, UserRoleViewModel>().AddDefaultTokenProviders();
services.AddTransient<IUserStore<UserViewModel>, UserStore>();
services.AddTransient<IRoleStore<UserRoleViewModel>, RoleStore>();
services.ConfigureApplicationCookie(options =>
{
options.Cookie.HttpOnly = true;
options.LoginPath = "/Login";
options.LogoutPath = "/Logout";
});
}
UserStore 类
public class UserStore : IUserStore<UserViewModel>, IUserPasswordStore<UserViewModel>, IUserEmailStore<UserViewModel>, IUserRoleStore<UserRoleViewModel>
{
....
RoleStore 类
public class RoleStore : IRoleStore<UserRoleViewModel>,IUserRoleStore<UserRoleViewModel>
{
....
UserViewModel 类
public class UserViewModel
{
[Key, Required]
public int Id { get; set; }
[Required, MaxLength(128)]
public string UserName { get; set; }
[Required, MaxLength(1024)]
public string Password { get; set; }
public virtual ICollection<UserRoleViewModel> UserRoles { get; set; }
}
UserRoleViewRoleModel 类
public class UserRoleViewModel
{
[Key, Required]
public int Id { get; set; }
[Required, ForeignKey(nameof(User))]
public int UserId { get; set; }
[Required, ForeignKey(nameof(Role))]
public int RoleId { get; set; }
public virtual RoleViewModel Role { get; set; }
public virtual UserViewModel User { get; set; }
}
RoleViewModel 类
public class RoleViewModel
{
[Key,Required]
public int RoleId { get; set; }
[Required]
public string RoleName { get; set; }
public virtual ICollection<UserRoleViewModel> UserRoles { get; set; }
}
**Calling Code**
//this works
var result = await signInManager.PasswordSignInAsync(user.UserName, user.Password, true, false);
//this fails
var test = await userManager.IsInRoleAsync(user, "Management");
//this fails
var roles = await userManager.GetRolesAsync(user);
错误
NotSupportedException:存储未实现IUserRoleStore。 Microsoft.AspNetCore.Identity.UserManager.GetUserRoleStore()
如果我的结构方式不正确,请原谅我,但我是来自ASP.Net Web窗体的新手。
答案 0 :(得分:1)
不确定,但似乎您忘记了在start up.cs文件中添加角色
services.AddDefaultIdentity<UserViewModel>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<DbContext>();
请在下面的链接中找到更多参考。 http://qaru.site/questions/16512353/store-does-not-implement-iuserrolestoretuser-aspnet-core-21-identity
答案 1 :(得分:0)
删除下面的行:
services.AddTransient,UserStore>();