将身份验证和标识迁移到 ASP.NET CoreMigrate Authentication and Identity to ASP.NET Core

作者:Steve SmithBy Steve Smith

在以前的文章中,我们配置从 ASP.NET MVC 项目迁移到 ASP.NET Core MVCIn the previous article, we migrated configuration from an ASP.NET MVC project to ASP.NET Core MVC. 本文将迁移注册、登录和用户管理功能。In this article, we migrate the registration, login, and user management features.

配置标识和成员身份Configure Identity and Membership

在 ASP.NET MVC 中, 使用Startup.Auth.csIdentityConfig.cs中的 ASP.NET Identity 配置身份验证和标识功能, 这些功能位于App_Start文件夹中。In ASP.NET MVC, authentication and identity features are configured using ASP.NET Identity in Startup.Auth.cs and IdentityConfig.cs, located in the App_Start folder. 在 ASP.NET Core MVC,这些功能在中配置Startup.csIn ASP.NET Core MVC, these features are configured in Startup.cs.

Microsoft.AspNetCore.Identity.EntityFrameworkCore安装和Microsoft.AspNetCore.Authentication.Cookies NuGet 包。Install the Microsoft.AspNetCore.Identity.EntityFrameworkCore and Microsoft.AspNetCore.Authentication.Cookies NuGet packages.

然后, 打开Startup.cs并更新Startup.ConfigureServices方法以使用实体框架和标识服务:Then, open Startup.cs and update the Startup.ConfigureServices method to use Entity Framework and Identity services:

public void ConfigureServices(IServiceCollection services)
{
    // Add EF services to the services container.
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

     services.AddMvc();
}

此时, 在上面的代码中引用了两个类型, 这些类型尚未从 ASP.NET MVC 项目迁移: ApplicationDbContext和。 ApplicationUserAt this point, there are two types referenced in the above code that we haven't yet migrated from the ASP.NET MVC project: ApplicationDbContext and ApplicationUser. 创建一个新模型文件夹中 ASP.NET Core 项目,并将两个类添加到它对应于这些类型。Create a new Models folder in the ASP.NET Core project, and add two classes to it corresponding to these types. 你将在 /Models/IdentityModels.cs中找到这些类的 ASP.NET MVC 版本, 但我们会在迁移的项目中对每个类使用一个文件, 因为这样做更为清晰。You will find the ASP.NET MVC versions of these classes in /Models/IdentityModels.cs, but we will use one file per class in the migrated project since that's more clear.

ApplicationUser.cs:ApplicationUser.cs:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;

namespace NewMvcProject.Models
{
  public class ApplicationUser : IdentityUser
  {
  }
}

ApplicationDbContext.cs:ApplicationDbContext.cs:

using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.Data.Entity;

namespace NewMvcProject.Models
{
    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 Core Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Core Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);
        }
    }
}

ASP.NET Core MVC 初学者 Web 项目不包括多的自定义的用户,或ApplicationDbContextThe ASP.NET Core MVC Starter Web project doesn't include much customization of users, or the ApplicationDbContext. 迁移实际应用时, 还需要迁移应用的用户和DbContext类的所有自定义属性和方法, 以及应用所使用的任何其他模型类。When migrating a real app, you also need to migrate all of the custom properties and methods of your app's user and DbContext classes, as well as any other Model classes your app utilizes. 例如, 如果DbContext DbSet<Album>具有, Album则需要迁移该类。For example, if your DbContext has a DbSet<Album>, you need to migrate the Album class.

将这些文件放入后,可通过更新其using语句对 Startup.cs 文件进行编译:With these files in place, the Startup.cs file can be made to compile by updating its using statements:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

现在, 我们的应用程序已准备好支持身份验证和标识服务。Our app is now ready to support authentication and Identity services. 只需将这些功能公开给用户。It just needs to have these features exposed to users.

迁移注册和登录逻辑Migrate registration and login logic

对于使用实体框架和 SQL Server 配置的应用和数据访问配置的标识服务, 我们已准备好添加注册和登录到应用的支持。With Identity services configured for the app and data access configured using Entity Framework and SQL Server, we're ready to add support for registration and login to the app. 回忆一下, 在迁移过程中, 我们在 _Layout中注释掉对 _LoginPartial的引用。Recall that earlier in the migration process we commented out a reference to _LoginPartial in _Layout.cshtml. 现在可以返回到该代码, 取消注释, 并添加必要的控制器和视图以支持登录功能。Now it's time to return to that code, uncomment it, and add in the necessary controllers and views to support login functionality.

取消注释@Html.Partial _Layout中的行:Uncomment the @Html.Partial line in _Layout.cshtml:

      <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
    </ul>
    @*@Html.Partial("_LoginPartial")*@
  </div>
</div>

现在, 将名为 _LoginPartial的新 Razor 视图添加到Views/Shared文件夹:Now, add a new Razor view called _LoginPartial to the Views/Shared folder:

用以下代码更新 _LoginPartial (替换其所有内容):Update _LoginPartial.cshtml with the following code (replace all of its contents):

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

@if (SignInManager.IsSignedIn(User))
{
    <form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
        <ul class="nav navbar-nav navbar-right">
            <li>
                <a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
            </li>
            <li>
                <button type="submit" class="btn btn-link navbar-btn navbar-link">Log out</button>
            </li>
        </ul>
    </form>
}
else
{
    <ul class="nav navbar-nav navbar-right">
        <li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
        <li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
    </ul>
}

此时, 您应该能够在浏览器中刷新站点。At this point, you should be able to refresh the site in your browser.

总结Summary

ASP.NET Core 引入 ASP.NET 标识功能更改。ASP.NET Core introduces changes to the ASP.NET Identity features. 在本文中,你看到了如何将 ASP.NET 标识的身份验证和用户管理功能迁移到 ASP.NET Core。In this article, you have seen how to migrate the authentication and user management features of ASP.NET Identity to ASP.NET Core.