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

作者:Rick AndersonBy Rick Anderson

ASP.NET Core 2.1 和更新版本提供作為Razor 類別庫ASP.NET Core 身分識別ASP.NET Core 2.1 and later provides ASP.NET Core Identity as a Razor Class Library. 包含身分識別的應用程式可以套用 scaffolder,以選擇性地新增包含在身分識別 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.

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

執行身分識別 scaffolder 時,會在專案目錄中建立ScaffoldingReadme。When the Identity scaffolder is run, a ScaffoldingReadme.txt file is created in the project directory. ScaffoldingReadme .txt檔案包含完成身分識別架構更新所需事項的一般指示。The ScaffoldingReadme.txt file contains general instructions on what's needed to complete the Identity scaffolding update. 本檔包含比ScaffoldingReadme更完整的指示。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. 當基架構識別時,不會產生服務或服務存根。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

執行身分識別 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. 例如,MVC 專案的 Razor Pages ~/Views/Shared/_Layout.cshtml ~/Pages/Shared/_Layout.cshtmlFor 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

Add-Migration命令的 "CreateIdentitySchema" 名稱參數是任意的。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

執行身分識別 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. 例如,MVC 專案的 Razor Pages ~/Views/Shared/_Layout.cshtml ~/Pages/Shared/_Layout.cshtmlFor 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中設定。Identity 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

Add-Migration命令的 "CreateIdentitySchema" 名稱參數是任意的。The "CreateIdentitySchema" name parameter for the Add-Migration command is arbitrary. "CreateIdentitySchema"描述遷移。"CreateIdentitySchema" describes the migration.

啟用驗證Enable authentication

Startup 類別的 Configure 方法中,在 UseStaticFiles 之後呼叫UseAuthenticationIn 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.

某些身分識別選項會在區域/身分識別/IdentityHostingStartup中設定。Some Identity options are configured in Areas/Identity/IdentityHostingStartup.cs. 如需詳細資訊,請參閱IHostingStartupFor more information, see IHostingStartup.

將身分識別 Scaffold 至沒有現有授權的 MVC 專案Scaffold identity into an MVC project without existing 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. 例如,MVC 專案的 Razor Pages ~/Views/Shared/_Layout.cshtml ~/Pages/Shared/_Layout.cshtmlFor 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檔案移至Views/shared/_LoginPartial。 cshtmlMove the Pages/Shared/_LoginPartial.cshtml file to Views/Shared/_LoginPartial.cshtml

身分識別是在Areas/identity/IdentityHostingStartup中設定。Identity 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

Add-Migration命令的 "CreateIdentitySchema" 名稱參數是任意的。The "CreateIdentitySchema" name parameter for the Add-Migration command is arbitrary. "CreateIdentitySchema"描述遷移。"CreateIdentitySchema" describes the migration.

@No__t-1 之後呼叫UseAuthenticationCall 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.

刪除頁面/共用資料夾,以及該資料夾中的檔案。Delete the Pages/Shared folder and the files in that folder.

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

若要維持身分識別 UI 的完全控制,請執行身分識別 scaffolder,然後選取 [覆寫所有檔案]。To maintain full control of the Identity UI, run the Identity scaffolder and select Override all files.

下列反白顯示的程式碼顯示在 ASP.NET Core 2.1 web 應用程式中,將預設身分識別 UI 取代為身分識別的變更。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();

下列程式碼會設定LoginPathLogoutPathAccessDeniedPathThe 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