我即将开始一个项目,我将使用MVC5.但是,由于我想使用IoC并稍后重用我的用户表,并向其添加自定义内容,我发现很难看到我如何使用MVC5附带的新Identity框架.
我越来越关注基本形式的认证.你有什么解决方案?
我的需求:
我一直在寻找答案,但我看到的一切都是在控制器中硬编码的.
你是怎么解决的?您是从头开始编写的,还是可以绑定到可以扩展到其他.NET平台的东西,如WCF和WPF?
以下代码直接来自默认ASP.NET MVC 5模板中的AccountController.它做的第一件事是Bastard Injection.
[Authorize]
public class AccountController : Controller
{
public AccountController()
: this(
new UserManager<ApplicationUser>(
new UserStore<ApplicationUser>(
new ApplicationDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
}
Run Code Online (Sandbox Code Playgroud)
接受的答案将交给那个人,它向我展示了他们所做的事情,其中包含了上述要求
c# authentication asp.net-mvc entity-framework dependency-injection
基于在GitHub 上发布的实现,我制作了自己的UserStore和RoleStore,它们不使用实体框架(在附加到真实数据库之前,我目前只需要内存中的一个简单用户列表)。为了能够做到这一点,我不得不更改注册。我已经编写了自己的IdentityEntityFrameworkBuilderExtensions,没有 DbContext 和 TryAddSingleton 而不是 TryAddScoped,所以一旦初始化用户列表可以持续整个应用程序生命周期。问题是,Dispose 方法被调用了这么多次……我没有处理任何东西,但是调用的次数太多了。是不是因为我做了UserStore和RoleStore 单例,即使其他一切都按照它们的范围工作?
第二件事是,完成工作UserStore所需的最低限度是什么?
danludwig写道:你只需要IUserStore和IUserPasswordStore,这是非常有可能的,因为我做了一个店实现这两个接口和一个Rolestore的与IRoleStore并seemd工作。由于在启动类中的一部分,我也做了RoleStoreservices.AddIdentity<ApplicationUser, IdentityRole>()。我为ASP.NET Core Web 应用程序使用了实体框架授权模板(带有个人用户帐户)。
Arve Systad 和 Anderson Matos写道,你需要这 8 个:
IUserStore<TUser>IUserPasswordStore<TUser>IUserTwoFactorStore<TUser>IUserClaimStore<TUser>IRoleStore<TRole>IUserSecurityStampStore<TUser, string>IUserRoleStore<TUser, string>UserManager<TUser>删除所有实体框架包后,我了解到它只提供了实现的UserStore和RoleStore(基于来自 GitHub 的源代码):