.net identity scaffold

这里的scaffold指的是把identity的默认注册/登录/重置密码等功能全部提取出来。

背景

默认添加identity后,如果也添加了AddDefaultUI,那么会有默认的identity各种页面完成身份认证相关的各种功能。

首先identity的功能比较多,接口文档可以说是基本没有的,使用起来非常难,如果要从头搭建,我试了一下基本的登录功能都参考了很多文章才能完成,更不要说第三方登录、找回、注册等功能了。

一开始也是不想直接用内置页面的(使用这个功能竟然要自带页面。。),后来来实在搞不定,只能在原有的基础上改了。不同于之前.net版本的Identity,现在的Identity的页面都是内置在库文件里的,需要通过脚手架工具才能引出来

方法

其实参考这篇文章就可以,我这个是用的命令行来操作的,相比通过vs,可能稍微有一些泛用性

脚手架工具

dotnet tool install -g dotnet-aspnet-codegenerator

这个包不知道干嘛的,但是也得装

这里可以不用执行dotnet restore,用到的时候会自动执行的

dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design

生成代码

dotnet aspnet-codegenerator identity

这个会把所有的页面都搭建出来,还会生成IdentityHostingStartup.cs文件以及{ProjectName}IdentityDbContext名称的DbContext,如果都在StartUp里注册Identity,那么需要删掉这些文件。

生成Identity各个页面在Areas/Identity/Pages/Account下面,是Razor页面,可以按需要修改了。

注册identity

StartUp中不要忘记注册Identity:

 services.AddIdentity<ApplicationUser, ApplicationRole>(
            options =>
            {
                options.Password.RequireDigit = false;
                options.Password.RequiredLength = 4;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireLowercase = false;
                options.User.AllowedUserNameCharacters = null;
            })
            //.AddDefaultUI(UIFramework.Bootstrap4) 这个不需要了
           .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
原文地址:https://www.cnblogs.com/mosakashaka/p/12608877.html