Я пытаюсь реализовать (порт от более старого проекта MVC 5) разрешения на основе группы на ядре .NET, и я получаю ошибкуEntityFrameworkCore - Невозможно создать экземпляр абстрактного класса или интерфейса
Невозможно создать экземпляр абстрактного класса или интерфейса
UserStore
.
var manager = new ApplicationUserManager(
new UserStore<ApplicationUser,
ApplicationRole,
DbContext,
string,
ApplicationUserClaim,
ApplicationUserRole,
ApplicationUserLogin,
IdentityUserToken<string>>
(context.Get<ApplicationDbContext>())
);
Я не использовал эту ошибку на оригинальном проекте MVC 5, но я не могу решить эту проблему на .Net Core. Пожалуйста помоги.
Это файл config.cs.
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using System;
using System.Threading.Tasks;
using System.Web;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Logging;
namespace MFMIS.Models
{
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
public ApplicationUserManager(IUserStore<ApplicationUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<ApplicationUser> passwordHasher, IEnumerable<IUserValidator<ApplicationUser>> userValidators, IEnumerable<IPasswordValidator<ApplicationUser>> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<ApplicationUser>> logger)
: base(store,optionsAccessor,passwordHasher,userValidators,passwordValidators,keyNormalizer,errors,services,logger)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
IOwinContext context)
{
var manager = new ApplicationUserManager(new UserStore<ApplicationUser, ApplicationRole, DbContext, string, ApplicationUserClaim, ApplicationUserRole, ApplicationUserLogin, IdentityUserToken<string>>(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug in here.
manager.RegisterTwoFactorProvider("PhoneCode", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is: {0}"
});
manager.RegisterTwoFactorProvider("EmailCode", new EmailTokenProvider<ApplicationUser>
{
Subject = "SecurityCode",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
// Configure the RoleManager used in the application. RoleManager is defined in the ASP.NET Identity core assembly
public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
public ApplicationRoleManager(IRoleStore<ApplicationRole> roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
{
return new ApplicationRoleManager(new ApplicationRoleStore(context.Get<ApplicationDbContext>()));
}
}
// This is useful if you do not want to tear down the database each time you run the application.
// public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
// This example shows you how to create a new database if the Model changes
public class ApplicationDbInitializer : DropCreateDatabaseAlways<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
InitializeIdentityForEF(context);
base.Seed(context);
}
//Create [email protected] with [email protected] in the Admin role
public static void InitializeIdentityForEF(ApplicationDbContext db)
{
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
const string name = "[email protected]";
const string password = "[email protected]";
const string roleName = "Admin";
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new ApplicationRole(roleName);
var roleresult = roleManager.Create(role);
}
var user = userManager.FindByName(name);
if (user == null)
{
user = new ApplicationUser { UserName = name, Email = name, EmailConfirmed = true };
var result = userManager.Create(user, password);
result = userManager.SetLockoutEnabled(user.Id, false);
}
var groupManager = new ApplicationGroupManager();
var newGroup = new ApplicationGroup("SuperAdmins", "Full Access to All");
groupManager.CreateGroup(newGroup);
groupManager.SetUserGroups(user.Id, new string[] { newGroup.Id });
groupManager.SetGroupRoles(newGroup.Id, new string[] { role.Name });
}
}
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public ApplicationSignInManager(ApplicationUserManager userManager, IAuthenticationManager authenticationManager) :
base(userManager, authenticationManager)
{ }
public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
}
public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
{
return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
}
}
}
В случае, если вы хотите попробовать проект локально для проверки зависимостей, here's the link.
Я не нужны эти много параметров, но базовый класс UserManager нужно все those.Have пытался выяснить это для многих time.All Я хочу это 'общественного ApplicationUserManager (IUserStore магазин) : база (магазин) { } '. Можете ли вы мне помочь? –
shubhamr
Не знаете, что вам нужно, но вы можете попытаться найти реализации по умолчанию, например [PasswordHasher] (https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNetCore/Identity/PasswordHasher -TUser/index.html? Highlight = passwordhasher) и [UserValidator] (https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNetCore/Identity/UserValidator-TUser/index.html? highlight = uservalidator) Вы можете попытаться найти другие в документации. Кстати, вы говорите, что это порт из старого проекта. Была ли также часть «ApplicationUserManager» этого старого проекта? – suwik
Да, здесь https://github.com/TypecastException/AspNetIdentity2GroupPermissions/tree/master/AspNetIdentity2GroupPermissions – shubhamr