Asp.Net Core Identity 是.Net自带的身份认证系统,支持用户界面 (UI) 登录功能,并且管理用户、密码、配置文件数据、角色、声明、令牌、电子邮件确认等等。使用Visual Studio创建带有identity的项目时,使用SqlServer作为缺省的数据库,本文介绍如何改造为多种数据库支持。

首先,使用Visual Studio 2022创建一个新的Asp.Net Core Web项目,名称为TestIdentity,选择身份认证类型为个人账户:



创建的项目结构如下:



在Data目录下保存的是身份认证的DbContext,名称为ApplicationDbContext,还有基于SqlServer的迁移文件。我们所要做的第一件事情是将SqlServer部分移动到另一个项目中,然后再增加对其它数据库类型的支持。

现在我们在解决方案中创建一个新的类库项目,名称为IdentityEF,在这个项目中安装包Microsoft.AspNetCore.Identity.EntityFrameworkCore。然后将ApplicationDbContext移动到这个项目中。



然后我们再创建另一个类库项目,负责SqlServer数据库的迁移,名称为IdentityEF.SqlServer,在这个项目中安装包Microsoft.EntityFrameworkCore.SqlServer和Microsoft.EntityFrameworkCore.Tools,还要增加对IdentityEF的项目引用,然后将TestIdentity中Data目录下的Migrations子目录移动到这个项目中:

然后在这个项目中增加新的类DbContextFactory,代码如下:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestIdentity.Data; namespace IdentityEF.SqlServer
{
public class DbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=aspnet-TestIdentity-53bc9b9d-9d6a-45d4-8429-2a2761773502;Trusted_Connection=True;MultipleActiveResultSets=true",
x => x.MigrationsAssembly("IdentityEF.SqlServer"));
return new ApplicationDbContext(optionsBuilder.Options);
}
}
}

请注意,上面的数据库名称与TestIdentity项目中appsettings.json中定义的DefaultConnection是一样的,这样,生成的数据库在TestIdentity中可以直接使用。

{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-TestIdentity-53bc9b9d-9d6a-45d4-8429-2a2761773502;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

再增加一个依赖注入扩展IdentityEFExtension,方便在Web应用中的引用:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestIdentity.Data; namespace IdentityEF.SqlServer
{
public static class IdentityEFExtension
{
public static IServiceCollection AddIdentityEFSqlServer(this IServiceCollection services, IConfiguration Configuration)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
x => x.MigrationsAssembly("IdentityEF.SqlServer")));
return services;
}
}
}

到这里,改造基本完毕,在Web应TestIdentity项目中,增加对这两个项目的引用,然后改造Program.cs,将原有的部分注释掉,增加AddIdentityEFSqlServer:

//// Add services to the container.
//var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
//builder.Services.AddDbContext<ApplicationDbContext>(options =>
// options.UseSqlServer(connectionString));
//builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddIdentityEFSqlServer(builder.Configuration);

现在,可以在包管理器中,使用Update-Database创建数据库。首先,将IdentityEF.SqlServer项目设置为启动项目,在包管理器中,将缺省项目也设置为IdentityEF.SqlServer:



然后运行Update-Database,顺利的化,数据库就生成了。将启动项目改回到TestIdentity,运行项目,我们可以注册用户并进行登录了。到这里,针对SqlServer的部分已经从Web项目中分离,现在,我们增加对其它数据库类型的支持,比如,我们增加Sqlite的支持。

创建一个新的类库,名称为IdentityEF.Sqlite,增加程序包Microsoft.EntityFrameworkCore.Sqlite和Microsoft.EntityFrameworkCore.Tools,还要增加对IdentityEF的项目引用,然后增加DbContextFactory:

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using TestIdentityEF.Data; namespace IdentityEF.Sqlite
{
public class DbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
{
public ApplicationDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
optionsBuilder.UseSqlite("DataSource=mydatabase.db;",
x => x.MigrationsAssembly("IdentityEF.Sqlite")); return new ApplicationDbContext(optionsBuilder.Options);
}
}
}

还增加依赖注入扩展:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestIdentity.Data; namespace IdentityEF.Sqlite
{
public static class IdentityEFExtension
{
public static IServiceCollection AddIdentityEFSqlite(this IServiceCollection services, IConfiguration Configuration)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("IdentityConnection"),
x => x.MigrationsAssembly("IdentityEF.Sqlite")));
return services;
}
}
}

项目的结构如下:



现在,我们需要生成迁移文件和数据库。将项目IdentityEF.Sqlite设置为启动项目,在程序包管理器中,将IdentityEF.Sqlite设置为缺省项目:



在程序包管理器中运行:

Add-Migration init

如果一切顺利,在项目文件中会增加迁移文件:



然后运行Update-Database,我们会发现,项目中多了db文件:



最后,改造一下Web应用,使其支持Sqlite数据库,并且可以通过配置文件进行切换。在项目中增加对IdentityEF.Sqlite的引用,然后修改Program.cs:

if (builder.Configuration["DbType"]=="SqlServer")
builder.Services.AddIdentityEFSqlServer(builder.Configuration);
else
builder.Services.AddIdentityEFSqlite(builder.Configuration);

在配置文件中使用DbType切换数据库的类型:

{
"ConnectionStrings": {
//"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-TestIdentity-53bc9b9d-9d6a-45d4-8429-2a2761773502;Trusted_Connection=True;MultipleActiveResultSets=true",
"DefaultConnection": "DataSource=D:\\Asp.Net Core\\TestIdentityEF\\IdentityEF.Sqlite\\mydatabase.db"
},
"DbType": "Sqlite",
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

完整的项目代码可以从github下载:https://github.com/zhenl/TestIdentityEF

Asp.Net Core Identity 多数据库支持的更多相关文章

  1. ASP.NET Core Identity自定义数据库结构和完全使用Dapper而非EntityFramework Core

    前言 原本本节内容是不存在的,出于有几个人问到了我:我想使用ASP.NET Core Identity,但是我又不想使用默认生成的数据库表,想自定义一套,我想要使用ASP.NE Core Identi ...

  2. ASP.NET Core Identity Hands On(1)——Identity 初次体验

    ASP.NET Core Identity是用于构建ASP.NET Core Web应用程序的成员资格系统,包括成员资格.登录和用户数据存储 这是来自于 ASP.NET Core Identity 仓 ...

  3. ASP.NET Core Identity Hands On(2)——注册、登录、Claim

    上一篇文章(ASP.NET Core Identity Hands On(1)--Identity 初次体验)中,我们初识了Identity,并且详细分析了AspNetUsers用户存储表,这篇我们将 ...

  4. ASP.NET Core Identity 实战(2)——注册、登录、Claim

    上一篇文章(ASP.NET Core Identity Hands On(1)--Identity 初次体验)中,我们初识了Identity,并且详细分析了AspNetUsers用户存储表,这篇我们将 ...

  5. ASP.NET Core Identity 框架 - ASP.NET Core 基础教程 - 简单教程,简单编程

    原文:ASP.NET Core Identity 框架 - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core Identity 框架 前面我们使用了 N 多个章节, ...

  6. Asp.Net Core Identity 完成注册登录

    Identity是Asp.Net Core全新的一个用户管理系统,它是一个完善的全面的庞大的框架,提供的功能有: 创建.查询.更改.删除账户信息 验证和授权 密码重置 双重身份认证 支持扩展登录,如微 ...

  7. Asp.Net Core Identity 隐私数据保护

    前言 Asp.Net Core Identity 是 Asp.Net Core 的重要组成部分,他为 Asp.Net Core 甚至其他 .Net Core 应用程序提供了一个简单易用且易于扩展的基础 ...

  8. 从零搭建一个IdentityServer——集成Asp.net core Identity

    前面的文章使用Asp.net core 5.0以及IdentityServer4搭建了一个基础的验证服务器,并实现了基于客户端证书的Oauth2.0授权流程,以及通过access token访问被保护 ...

  9. IdentityServer(12)- 使用 ASP.NET Core Identity

    IdentityServer具有非常好的扩展性,其中用户及其数据(包括密码)部分你可以使用任何想要的数据库进行持久化. 如果需要一个新的用户数据库,那么ASP.NET Core Identity是你的 ...

随机推荐

  1. java中downcast向下转型到底有什么用

    What is the point of downcast? 当一个方法只有子类才有,马克-to-win:不是说基类和子类都有,开始时又是基类指针指向派生类,这时就需要downcast, see th ...

  2. MySQL外键约束On Delete和On Update的使用

    On Delete和On Update都有Restrict,No Action, Cascade,Set Null属性.现在分别对他们的属性含义做个解释. ON DELETE restrict(约束) ...

  3. JavaScript脚本延迟加载的方式有哪些?

    延迟加载就是等页面加载完成之后再加载 JavaScript 文件. js 延迟加载有助于提高页面加载速度. 一般有以下几种方式: defer 属性: 给 js 脚本添加 defer 属性,这个属性会让 ...

  4. LC-977

    给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序. 示例 1: 输入:nums = [-4,-1,0,3,10] 输出:[0,1,9,1 ...

  5. 得到一个a(10)到b(20)的随机数。包括10和20

  6. 手把手带你入门ECharts

    1.什么是ECharts ECharts,缩写来自Enterprise Charts,商业级数据图表,是来自百度商业前端数据可视化团队EFE的一个开源的纯Javascript的图表库,可以流畅的运行在 ...

  7. PicLite 开发日志 v0.0.2

    PicLite 开发日志 (v0.0.2) 感谢您阅读本片文章! Gitee 地址:https://gitee.com/XiaoQuQuSD/pic-lite. 新增功能 添加复制 url 的格式选项 ...

  8. 尤娜故事-迷雾-springboot扮酷小技巧

    前情回顾 从前,有一个简单的通道系统叫尤娜-- 尤娜系统的第一次飞行中换引擎的架构垂直拆分改造 四种常用的微服务架构拆分方式 尤娜,我去面试了 正文 我回到日常的尤娜系统建设中,最近事情比较少,总有一 ...

  9. openstack PCI透传(GPU)

    描述 kolla-ansible部署openstack的GPU透传方法 一.gpu物理服务器配置 在gpu服务器上主启用IOMMU 确认内核⽀支持iommu $ cat /proc/cmdline | ...

  10. 攻防世界-MISC:ext3

    这是攻防世界新手练习区的第九题,题目如下: 点击下载附件1,通过题目描述可知这是一个Linux系统光盘,用010editor打开,搜索flag,发现存在flag.txt文件 将该文件解压,找到flag ...