对于没有包含认证(authentication),的项目,你可以使用基架(scaffolder)把 Identity的程序集包加入到项目中,并且选择性的添加Identity的代码进行生成。
虽然基架已经生成了很多必须的代码,但是你仍然需要更新你的项目来完善这个过程。
这篇文章主要就是解释完善Identity基架进行更新的一些步骤
当Identity基架添加以后,一个ScaffoldingReadme.txt 文件就被创建了,这里面会包含一些完善Identity基架的说明。如下
ScaffoldingReadme.txt
Support for ASP.NET Core Identity was added to your project 支持把ASP.NET Core Identity添加到你的项目里 - The code for adding Identity to your project was generated under Areas/Identity. 添加Identity生成的代码在Areas/Identity下面
关于Identity 相关的服务配置在Areas/Identity/IdentityHostingStartup.cs 中可以被找到 Configuration of the Identity related services can be found in the Areas/Identity/IdentityHostingStartup.cs file. UI需要支持静态文件,可以在Configure方法中调用 app.UseStaticFiles() The generated UI requires support for static files. To add static files to your app: 1. Call app.UseStaticFiles() from your Configure method
要使用ASP.NET Core Identity,你还需要允许认证(authentication),可以在Configure方法中调用 app.UseAuthentication(),在调用静态文件之后做此设置 To use ASP.NET Core Identity you also need to enable authentication. To authentication to your app: 1. Call app.UseAuthentication() from your Configure method (after static files)
UI 要求MVC,可以通过在 Configure 方法中调用app.UseMvc(),在认证之后调用,
另外还需要在 ConfigureServices 中增加调用 services.AddMvc() The generated UI requires MVC. To add MVC to your app: 1. Call services.AddMvc() from your ConfigureServices method 2. Call app.UseMvc() from your Configure method (after authentication) Apps that use ASP.NET Core Identity should also use HTTPS. To enable HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.
这篇文章会提供更详细的说明
- 把Identity基架添加到一个空项目
- 把Identity基架添加到一个 不存在 认证(authentication)的 Razor项目(即项目中原来不存在认证的项目)
- 把Identity基架添加到一个 存在 认证(authentication)的 Razor项目(即项目中原来存在认证的项目)
- 把Identity基架添加到一个 不存在 认证(authentication)的 MVC项目(即项目中原来不存在认证的项目)
- 把Identity基架添加到一个 存在 认证(authentication)的 MVC项目(即项目中原来存在认证的项目)
- 创建一个完全的Identity UI (认证界面) 资源
把Identity基架添加到一个空项目
1.首先,准备一个空项目
- 文件->新建->项目
- ASP.NET Core web应用,项目名EmptyForIdentity,确定
- 选择空项目
操作如图:
2.添加Identity基架
- 在项目上右键,添加->新搭建基架的项目
- 标识->添加
然后,选择文件;
在这步,如果有布局页,可以选择现有的布局页;
这里没有没有布局页,也不需要指定一个新的布局页,就空着就可以了,它会自动生成一个新的布局页;
然后选择你需要的功能页面,这里选择的是登录功能页面,登录功能页面,注册功能页面;
再选择数据上下文,这里,如果存在的话,一样可以选择已经存在的;但是,在这个空项目中,是没有数据上下文的,所以这里直接点击加号,
新增一个即可。
点击添加
3.在StartUp文件类中,增加如下代码:
public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) {
//新增的代码 services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
//注释的为空项目中原来的代码 //if (env.IsDevelopment()) //{ // app.UseDeveloperExceptionPage(); //} //app.Run(async (context) => //{ // await context.Response.WriteAsync("Hello World!"); //}); if (env.IsDevelopment()) { app.UseDeveloperExcep