ASP.NET Core 專案中的 scaffold 身分識別Scaffold Identity in ASP.NET Core projects

作者:Rick AndersonBy Rick Anderson

ASP.NET Core 2.1 和更新版本可ASP.NET Core Identity作為Razor 類別庫ASP.NET Core 2.1 and later provides ASP.NET Core Identity as a Razor Class Library. 包含身分識別應用程式,可以套用到建構者選擇性地加入 包含在識別 Razor 類別庫 (RCL) 的原始程式碼。Applications that include Identity can apply the scaffolder to selectively add the source code contained in the Identity Razor Class Library (RCL). 建議您產生原始程式碼,以便能夠修改程式碼並變更行為。You might want to generate source code so you can modify the code and change the behavior. 例如,您可以指示 Scaffolder 產生註冊使用的程式碼。For example, you could instruct the scaffolder to generate the code used in registration. 產生的程式碼優先於身分識別 RCL 中的相同程式碼。Generated code takes precedence over the same code in the Identity RCL. 若要完整掌控 UI,並使用預設 RCL,請參閱下節建立完整的身分識別 UI 來源To gain full control of the UI and not use the default RCL, see the section Create full identity UI source.

執行的應用程式包含驗證可以套用 scaffolder 新增 RCL 識別套件。Applications that do not include authentication can apply the scaffolder to add the RCL Identity package. 您可以選擇選取要產生的身分識別程式碼。You have the option of selecting Identity code to be generated.

雖然框架產生大部分的必要的程式碼,您必須更新專案,以完成程序。Although the scaffolder generates most of the necessary code, you'll have to update your project to complete the process. 本文件說明完成識別 scaffolding 更新所需的步驟。This document explains the steps needed to complete an Identity scaffolding update.

執行身分識別框架時, ScaffoldingReadme.txt專案目錄中建立檔案。When the Identity scaffolder is run, a ScaffoldingReadme.txt file is created in the project directory. ScaffoldingReadme.txt檔案包含需要的完成識別 scaffolding 更新內容的一般指示。The ScaffoldingReadme.txt file contains general instructions on what's needed to complete the Identity scaffolding update. 本文件包含更詳細的說明,比ScaffoldingReadme.txt檔案。This document contains more complete instructions than the ScaffoldingReadme.txt file.

我們建議使用顯示檔案的差異,並可讓您將變更原始檔控制系統。We recommend using a source control system that shows file differences and allows you to back out of changes. 執行身分識別 scaffolder 之後檢查所做的變更。Inspect the changes after running the Identity scaffolder.

注意

使用時,服務不需要雙因素驗證帳戶確認和密碼復原,以及其他與身分識別的安全性功能。Services are required when using Two Factor Authentication, Account confirmation and password recovery, and other security features with Identity. Scaffolding 身分識別時,不會產生服務或服務虛設常式。Services or service stubs aren't generated when scaffolding Identity. 若要啟用這些功能的服務必須手動加入。Services to enable these features must be added manually. 例如,請參閱需要電子郵件確認For example, see Require Email Confirmation.

Scaffold 的身分識別至空專案Scaffold identity into an empty project

執行身分識別框架:Run the Identity scaffolder:

  • 方案總管,以滑鼠右鍵按一下專案 >新增 > 新增 Scaffold 項目From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • 從左窗格新增 Scaffold對話方塊中,選取識別 > 新增From the left pane of the Add Scaffold dialog, select Identity > ADD.
  • 在 [ ADD 身分識別] 對話方塊中,選取您想要的選項。In the ADD Identity dialog, select the options you want.
    • 選取現有的版面配置頁面,或您的版面配置檔將會覆寫以不正確的標記。Select your existing layout page, or your layout file will be overwritten with incorrect markup. 比方說~/Pages/Shared/_Layout.cshtmlRazor 頁面~/Views/Shared/_Layout.cshtmlMVC 專案For example ~/Pages/Shared/_Layout.cshtml for Razor Pages ~/Views/Shared/_Layout.cshtml for MVC projects
    • 選取 + 來建立新的按鈕資料內容類別Select the + button to create a new Data context class.
  • 選取 新增Select ADD.

加入下列反白顯示的呼叫Startup類別:Add the following highlighted calls to the Startup class:

public class Startup
{        
    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();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseMvc();
    }
}

UseHsts 是建議但非必要。UseHsts is recommended but not required. 請參閱HTTP Strict Transport 安全性通訊協定如需詳細資訊。See HTTP Strict Transport Security Protocol for more information.

產生的識別資料庫程式碼需要Entity Framework Core 移轉The generated Identity database code requires Entity Framework Core Migrations. 建立移轉並更新資料庫。Create a migration and update the database. 例如,執行下列命令:For example, run the following commands:

在 Visual Studio Package Manager Console:In the Visual Studio Package Manager Console:

Add-Migration CreateIdentitySchema
Update-Database

「 CreateIdentitySchema"name 參數,如Add-Migration是任意的命令。The "CreateIdentitySchema" name parameter for the Add-Migration command is arbitrary. "CreateIdentitySchema" 描述如何移轉。"CreateIdentitySchema" describes the migration.

Scaffold 的身分識別至 Razor 專案沒有現有的授權Scaffold identity into a Razor project without existing authorization

執行身分識別框架:Run the Identity scaffolder:

  • 方案總管,以滑鼠右鍵按一下專案 >新增 > 新增 Scaffold 項目From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • 從左窗格新增 Scaffold對話方塊中,選取識別 > 新增From the left pane of the Add Scaffold dialog, select Identity > ADD.
  • 在 [ ADD 身分識別] 對話方塊中,選取您想要的選項。In the ADD Identity dialog, select the options you want.
    • 選取現有的版面配置頁面,或您的版面配置檔將會覆寫以不正確的標記。Select your existing layout page, or your layout file will be overwritten with incorrect markup. 比方說~/Pages/Shared/_Layout.cshtmlRazor 頁面~/Views/Shared/_Layout.cshtmlMVC 專案For example ~/Pages/Shared/_Layout.cshtml for Razor Pages ~/Views/Shared/_Layout.cshtml for MVC projects
    • 選取 + 來建立新的按鈕資料內容類別Select the + button to create a new Data context class.
  • 選取 新增Select ADD.

已在中設定身分識別Areas/Identity/IdentityHostingStartup.csIdentity is configured in Areas/Identity/IdentityHostingStartup.cs. 如需詳細資訊,請參閱 < IHostingStartupfor more information, see IHostingStartup.

移轉、 UseAuthentication 和版面配置Migrations, UseAuthentication, and layout

產生的識別資料庫程式碼需要Entity Framework Core 移轉The generated Identity database code requires Entity Framework Core Migrations. 建立移轉並更新資料庫。Create a migration and update the database. 例如,執行下列命令:For example, run the following commands:

在 Visual Studio Package Manager Console:In the Visual Studio Package Manager Console:

Add-Migration CreateIdentitySchema
Update-Database

「 CreateIdentitySchema"name 參數,如Add-Migration是任意的命令。The "CreateIdentitySchema" name parameter for the Add-Migration command is arbitrary. "CreateIdentitySchema" 描述如何移轉。"CreateIdentitySchema" describes the migration.

啟用驗證Enable authentication

Configure方法Startup類別中,呼叫UseAuthentication之後UseStaticFiles:In the Configure method of the Startup class, call UseAuthentication after UseStaticFiles:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication();

        app.UseMvc();
    }
}

UseHsts 是建議但非必要。UseHsts is recommended but not required. 請參閱HTTP Strict Transport 安全性通訊協定如需詳細資訊。See HTTP Strict Transport Security Protocol for more information.

版面配置變更Layout changes

選擇項:加入部分的登入 (_LoginPartial) 和配置檔案:Optional: Add the login partial (_LoginPartial) to the layout file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - RazorNoAuth8</title>

    <environment include="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
    </environment>
    <environment exclude="Development">
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a asp-page="/Index" class="navbar-brand">RazorNoAuth8</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-page="/Index">Home</a></li>
                    <li><a asp-page="/About">About</a></li>
                    <li><a asp-page="/Contact">Contact</a></li>
                </ul>
                <partial name="_LoginPartial" />
            </div>
        </div>
    </nav>

    <partial name="_CookieConsentPartial" />

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2018 - RazorNoAuth8</p>
        </footer>
    </div>

    <environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>
    <environment exclude="Development">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>

    @RenderSection("Scripts", required: false)
</body>
</html>

Scaffold Razor 專案具有授權的身分識別Scaffold identity into a Razor project with authorization

執行身分識別 scaffolder:Run the Identity scaffolder:

  • 方案總管,以滑鼠右鍵按一下專案 >新增 > 新增 Scaffold 項目From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • 從 [新增 Scaffold ] 對話方塊的左窗格中, 選取 [身分識別 > ] [新增]。From the left pane of the Add Scaffold dialog, select Identity > Add.
  • 在 [新增識別] 對話方塊中, 選取您想要的選項。In the Add Identity dialog, select the options you want.
    • 選取您現有的版面配置頁, 否則會以不正確的標記覆寫您的配置檔案。Select your existing layout page, or your layout file will be overwritten with incorrect markup. 選取現有 _的版面配置. cshtml檔案時,會覆寫該檔案。When an existing _Layout.cshtml file is selected, it is not overwritten.

例如: ~/Pages/Shared/_Layout.cshtml MVC 專案的~/Views/Shared/_Layout.cshtml Razor PagesFor example: ~/Pages/Shared/_Layout.cshtml for Razor Pages ~/Views/Shared/_Layout.cshtml for MVC projects

  • 若要使用現有的資料內容, 請至少選取一個要覆寫的檔案。To use your existing data context, select at least one file to override. 您必須至少選取一個檔案來新增資料內容。You must select at least one file to add your data context.
    • 選取您的資料內容類別。Select your data context class.
    • 選取 [新增] 。Select Add.
  • 若要建立新的使用者內容, 並可能建立身分識別的自訂使用者類別:To create a new user context and possibly create a custom user class for Identity:
    • 選取 + 來建立新的按鈕資料內容類別Select the + button to create a new Data context class.
    • 選取 [新增] 。Select Add.

注意:如果您要建立新的使用者內容, 就不需要選取要覆寫的檔案。Note: If you're creating a new user context, you don't have to select a file to override.

中所設定的一些身分識別選項Areas/Identity/IdentityHostingStartup.csSome Identity options are configured in Areas/Identity/IdentityHostingStartup.cs. 如需詳細資訊,請參閱 < IHostingStartupFor more information, see IHostingStartup.

MVC 專案中現有的授權而成的 scaffold 身分識別Scaffold identity into an MVC project without existing authorization

執行身分識別框架:Run the Identity scaffolder:

  • 方案總管,以滑鼠右鍵按一下專案 >新增 > 新增 Scaffold 項目From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • 從左窗格新增 Scaffold對話方塊中,選取識別 > 新增From the left pane of the Add Scaffold dialog, select Identity > ADD.
  • 在 [ ADD 身分識別] 對話方塊中,選取您想要的選項。In the ADD Identity dialog, select the options you want.
    • 選取現有的版面配置頁面,或您的版面配置檔將會覆寫以不正確的標記。Select your existing layout page, or your layout file will be overwritten with incorrect markup. 比方說~/Pages/Shared/_Layout.cshtmlRazor 頁面~/Views/Shared/_Layout.cshtmlMVC 專案For example ~/Pages/Shared/_Layout.cshtml for Razor Pages ~/Views/Shared/_Layout.cshtml for MVC projects
    • 選取 + 來建立新的按鈕資料內容類別Select the + button to create a new Data context class.
  • 選取 新增Select ADD.

選擇項:加入部分的登入 (_LoginPartial) 來Views/Shared/_Layout.cshtml檔案:Optional: Add the login partial (_LoginPartial) to the Views/Shared/_Layout.cshtml file:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>@ViewData["Title"] - MvcNoAuth3</title>

    <environment include="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
    </environment>
    <environment exclude="Development">
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>
</head>
<body>
    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a asp-area="" asp-controller="Home" asp-action="Index" class="navbar-brand">MvcNoAuth3</a>
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
                </ul>
                <partial name="_LoginPartial" />
            </div>
        </div>
    </nav>

    <partial name="_CookieConsentPartial" />

    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; 2018 - MvcNoAuth3</p>
        </footer>
    </div>

    <environment include="Development">
        <script src="~/lib/jquery/dist/jquery.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    </environment>
    <environment exclude="Development">
        <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.3.1.min.js"
                asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
                asp-fallback-test="window.jQuery"
                crossorigin="anonymous"
                integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
        </script>
        <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
                asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
                asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
                crossorigin="anonymous"
                integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
        </script>
        <script src="~/js/site.min.js" asp-append-version="true"></script>
    </environment>

    @RenderSection("Scripts", required: false)
</body>
</html>
  • 移動Pages/Shared/_LoginPartial.cshtml檔案Views/Shared/_LoginPartial.cshtmlMove the Pages/Shared/_LoginPartial.cshtml file to Views/Shared/_LoginPartial.cshtml

已在中設定身分識別Areas/Identity/IdentityHostingStartup.csIdentity is configured in Areas/Identity/IdentityHostingStartup.cs. 如需詳細資訊,請參閱 IHostingStartup。For more information, see IHostingStartup.

產生的識別資料庫程式碼需要Entity Framework Core 移轉The generated Identity database code requires Entity Framework Core Migrations. 建立移轉並更新資料庫。Create a migration and update the database. 例如,執行下列命令:For example, run the following commands:

在 Visual Studio Package Manager Console:In the Visual Studio Package Manager Console:

Add-Migration CreateIdentitySchema
Update-Database

「 CreateIdentitySchema"name 參數,如Add-Migration是任意的命令。The "CreateIdentitySchema" name parameter for the Add-Migration command is arbitrary. "CreateIdentitySchema" 描述如何移轉。"CreateIdentitySchema" describes the migration.

呼叫UseAuthentication之後UseStaticFiles:Call UseAuthentication after UseStaticFiles:

public class Startup
{

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseMvcWithDefaultRoute();
    }
}

UseHsts 是建議但非必要。UseHsts is recommended but not required. 請參閱HTTP Strict Transport 安全性通訊協定如需詳細資訊。See HTTP Strict Transport Security Protocol for more information.

Scaffold 的身分識別至具有授權的 MVC 專案Scaffold identity into an MVC project with authorization

執行身分識別 scaffolder:Run the Identity scaffolder:

  • 方案總管,以滑鼠右鍵按一下專案 >新增 > 新增 Scaffold 項目From Solution Explorer, right-click on the project > Add > New Scaffolded Item.
  • 從 [新增 Scaffold ] 對話方塊的左窗格中, 選取 [身分識別 > ] [新增]。From the left pane of the Add Scaffold dialog, select Identity > Add.
  • 在 [新增識別] 對話方塊中, 選取您想要的選項。In the Add Identity dialog, select the options you want.
    • 選取您現有的版面配置頁, 否則會以不正確的標記覆寫您的配置檔案。Select your existing layout page, or your layout file will be overwritten with incorrect markup. 選取現有 _的版面配置. cshtml檔案時,會覆寫該檔案。When an existing _Layout.cshtml file is selected, it is not overwritten.

例如: ~/Pages/Shared/_Layout.cshtml MVC 專案的~/Views/Shared/_Layout.cshtml Razor PagesFor example: ~/Pages/Shared/_Layout.cshtml for Razor Pages ~/Views/Shared/_Layout.cshtml for MVC projects

  • 若要使用現有的資料內容, 請至少選取一個要覆寫的檔案。To use your existing data context, select at least one file to override. 您必須至少選取一個檔案來新增資料內容。You must select at least one file to add your data context.
    • 選取您的資料內容類別。Select your data context class.
    • 選取 [新增] 。Select Add.
  • 若要建立新的使用者內容, 並可能建立身分識別的自訂使用者類別:To create a new user context and possibly create a custom user class for Identity:
    • 選取 + 來建立新的按鈕資料內容類別Select the + button to create a new Data context class.
    • 選取 [新增] 。Select Add.

注意:如果您要建立新的使用者內容, 就不需要選取要覆寫的檔案。Note: If you're creating a new user context, you don't have to select a file to override.

刪除頁/Shared資料夾,然後在該資料夾中的檔案。Delete the Pages/Shared folder and the files in that folder.

建立完整的身分識別 UI 來源Create full identity UI source

若要維護的身分識別使用者介面的完整控制權,執行身分識別的框架,然後選取覆寫所有檔案To maintain full control of the Identity UI, run the Identity scaffolder and select Override all files.

下列醒目提示的程式碼會顯示預設識別 UI 取代 ASP.NET Core 2.1 web 應用程式中的身分識別的變更。The following highlighted code shows the changes to replace the default Identity UI with Identity in an ASP.NET Core 2.1 web app. 您可能想要這樣做能夠完整控制身分識別 UI。You might want to do this to have full control of the Identity UI.

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<IdentityUser, IdentityRole>()
        // services.AddDefaultIdentity<IdentityUser>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddRazorPagesOptions(options =>
        {
            options.AllowAreas = true;
            options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
            options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
        });

    services.ConfigureApplicationCookie(options =>
    {
        options.LoginPath = $"/Identity/Account/Login";
        options.LogoutPath = $"/Identity/Account/Logout";
        options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
    });

    // using Microsoft.AspNetCore.Identity.UI.Services;
    services.AddSingleton<IEmailSender, EmailSender>();
}

預設身分識別會取代下列程式碼:The default Identity is replaced in the following code:

services.AddIdentity<IdentityUser, IdentityRole>()
    // services.AddDefaultIdentity<IdentityUser>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

下列程式碼設定LoginPathLogoutPath,並AccessDeniedPath:The following code sets the LoginPath, LogoutPath, and AccessDeniedPath:

services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = $"/Identity/Account/Login";
    options.LogoutPath = $"/Identity/Account/Logout";
    options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
});

註冊IEmailSender實作,例如:Register an IEmailSender implementation, for example:

// using Microsoft.AspNetCore.Identity.UI.Services;
services.AddSingleton<IEmailSender, EmailSender>();
public class EmailSender : IEmailSender
{
    public Task SendEmailAsync(string email, string subject, string message)
    {
        return Task.CompletedTask;
    }
}

其他資源Additional resources