Oct*_*pus 3 asp.net-identity asp.net-core-2.0 ef-core-2.0
通过在别处阅读的建议,角色是声明的子集,我正在寻找一种干净的方法来要求 ASP.NET Identity 中的 EF Core 实现不要在 VS 中的 ASP.NET Identity Core 2.0 模板中创建与角色相关的表2017. 只需要索赔。该模板使用
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
}
}
Run Code Online (Sandbox Code Playgroud)
而 IdentityDbContext 创建了这些 Roles 相关的表
如何在不操作迁移文件的情况下摆脱它们?
这在 ASP.NET Identity 中一直是可能的,但随着时间的推移变得更容易,因为约定已经从角色转向权限、操作、声明、谓词和其他更可重用和可维护的语义。多年来,我一直在我的 ASP.NET 项目中使用 Identity 和我预先存在的数据库模式(没有角色表)。我承认,由于 ASP.NET Identity 的繁琐复杂性,以及 ASP.NET 中发生的快节奏的开源代码更改以及完全缺乏人性化的文档,因此很难理解如何做到这一点在 API 参考中(完全是机器生成的样板文件)。
在 ASP.NET Core 之前,您可以通过覆盖UserManager和UserStore实现来做到这一点。通过使用无操作剔除 Role 请求,或者RoleAttribute使用更有用且对开发人员安全的实现(可能不是基于魔术字符串!)覆盖实现,Role 表的缺失不会被注意到。即使使用默认实现,如果您从未使用过默认 Role 属性实现或询问 Role 问题,这些表可能会被删除而不会产生任何后果。默认的 ASP.NET 脚手架都不依赖于角色。
在最初的 ASP.NET Core Identity 1.0/1.1 版本中,您是通过在UserStore没有可选IUserRoleStore接口的情况下实现的。可以在主要的 ASP.NET Core Identity 文档中找到有关这方面的信息。
从 ASP.NET Core 2.0(根据您的主要问题)开始,您可以通过从而IdentityUserContext不是派生上下文来更轻松地做到这一点IdentityDbContext,如下例所示。由于新的UserOnlyStore. AddIdentityStartup.cs 中的调用也需要替换为AddIdentityCore. AddIdentityCore如果您依赖其他标准身份验证功能,则需要一些额外的代码行,因为默认情况下它不会初始化 Cookie 或 TokenProvider。(如下所述,在 2.1 中,Startup不再需要对样板进行更改。)
在 ASP.NET Core 2.1/2.2(在撰写本文时为最新版本)中删除角色非常简单。下面是一个使用新项目来演示的示例:
创建一个新项目来证明身份,选择:
从新搭建的 Identity 项目中删除角色
ApplicationDbContext : IdentityDbContextApplicationDbContext : IdentityUserContext<IdentityUser>注意IdentityUserContext缺少角色,所以自定义键类型只需要 2 个参数
IdentityUserContext<IdentityUser<int>, int>AddDefaultIdentity<IdentityUser<int>>()如前指定更新/构建数据库架构以反映上述内容。在包管理器控制台中:
Add-Migration RemoveIdentitySchemaRolesUpdate-Database运行应用程序
| 归档时间: |
|
| 查看次数: |
2272 次 |
| 最近记录: |