2020年1月2日 星期四

Blazor 專案中,使用 Scaffold 身分識別修改登入頁面成為中文版

Blazor 專案中,使用 Scaffold 身分識別修改登入頁面成為中文版

更多關於 Blazor 教學影片,可以參考 Blazor 教學影片播放清單 或者 Blazor 快速體驗教學影片撥放清單。也歡迎訂閱本 .NET / Blazor / Xamarin.Forms 影片頻道 。


在這篇文章中,將會嘗試建立一個 Blazor Server side 的專案,並且該專案具有 個別使用者帳戶 身分驗證機制,接著,將會嘗試要來擴增選擇性地新增包含在身分識別 Razor 類別庫(RCL)中的原始程式碼,而在此,將會嘗試把 Login.cshtml 這個 Razor Page 頁面進行還原與客製。
在這篇文章所提到的專案原始碼,可以從 GitHub 下載

使用預設專案範本建立 Blazor 專案

想要進行這樣的專案開發練習,可以參考底下的操作步驟
  • 打開 Visual Studio 2019 開發工具
  • 當 [Visual Studio 2019] 對話窗出現之後,點選右下方的 [建立新的專案] 按鈕
  • 在 [建立新專案] 對話窗內,請找出 [Blazor 應用程式] 這個專案開發範本,並且點選這個專案開發範本
  • 請點選右下角 [下一步] 按鈕
  • 出現 [設定新的專案] 對話窗,輸入適當的 [專案名稱] 、 [位置] ,完成後,請點選右下角 [建立] 按鈕

    🕬 說明

    在這個範例程式碼中,將會建立一個 BlazorScaffoldIdentity 專案名稱
    #
  • 此時將會看到 [建立新的 Blazor 應用程式] 對話窗
  • 在該對話窗的右上方找到 [驗證] 文字,點選該文字下方的 [變更] 連結
  • 現在將會看到 [變更驗證] 這個對話窗
  • 請選擇 [個別使用者帳戶] 選項
  • 中間將會出現預設 [儲存應用程式的使用者帳戶] 下拉清單選項,使用預設值即可
  • 點選右下角的 [確定] 按鈕,關閉 [變更驗證] 這個對話窗
  • 此時回到了 [建立新的 Blazor 應用程式] 對話窗
  • 在該對話窗的右上角部分,將會出現 [驗證] 需求採用 [個別使用者帳戶]
  • 請點選右下角的 [建立] 按鈕
  • 此時,這個 Blazor 專案已經建立完成

🔑 注意事項

在建立練習專案的時候,物必須要在 [建立新的 Blazor 應用程式] 對話窗下,點選該對話窗右上方的 [驗證] 設定選項,並且要切換成為 請選擇 [個別使用者帳戶] 選項
#

執行並且查看登入畫面

  • 請開始執行這個具有身分識別的 Blazor 專案
  • 將會顯示底下螢幕截圖的網頁畫面
  • 請點選該網頁右上方的 [Log in] 連結文字
  • 此時,將會看到這個 Blazor 專案的登入頁面
    從這個登入頁面中,看到的是完全英文的畫面,而當想要修改或者擴增這個頁面的時候,將會發現在這個 Blazor 專案內並沒有相關的程式碼可以來做到這件事情
  • 請展開這個專案內的 [Areas] 資料夾內的其他資料夾,將會看到如下面螢幕截圖,確定沒有看到任何關於 Login 這個 Razor Page 頁面存在,當然,也就無法針對登入頁面做出任何修正

產生 Scaffold 身分識別 程式碼

  • 滑鼠右擊該專案節點
  • 選擇 [新增] > [新增 Scaffold 項目]
  • 現在將會看到 [新增 Scaffold 項目] 這個對話窗
  • 請點選左邊的 [識別] 標籤頁次,中間將會出現預設 [識別] 選項
  • 最後,請點選 [加入] 按鈕
  • 請等候安裝需要用到的 NuGet 套件,便會出現如下圖的 [新增 識別] 對話窗
  • 請在 [新增 識別] 對話窗 勾選 [Account\Login] 對話窗
  • 在 [資料內容類別] 下拉選單中,點選該下拉選單,選擇 ApplicationDbContext (BlazorScaffoldIdentity.Data) 這個選項
  • 完成後,請點選右下角的 [新增] 按鈕
  • 等候一段時間,相關程式碼就會產生出來
  • 下面螢幕截圖,是產生後的方案總管內容
    並且將會看到 [ScaffoldingReadMe.txt] 這個檔案產生,內容如下
Support for ASP.NET Core Identity was added to your project
- The code for adding Identity to your project was generated under Areas/Identity.

Configuration of the Identity related services can be found in the Areas/Identity/IdentityHostingStartup.cs file.


The generated UI requires support for static files. To add static files to your app:
1. Call app.UseStaticFiles() from your Configure method

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)

The generated UI requires MVC. To add MVC to your app:
1. Call services.AddMvc() from your ConfigureServices method
2. Call app.UseRouting() at the top your Configure method, and UseEndpoints() after authentication:
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapRazorPages();
    });

Apps that use ASP.NET Core Identity should also use HTTPS. To enable HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.
與這個專案最初產生的時候相比,在 [Area] > [Identity] 目錄下,多了一個 [IdentityHostingStartup.cs] 檔案,該檔案的內容如下
using System;
using BlazorScaffoldIdentity.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

[assembly: HostingStartup(typeof(BlazorScaffoldIdentity.Areas.Identity.IdentityHostingStartup))]
namespace BlazorScaffoldIdentity.Areas.Identity
{
    public class IdentityHostingStartup : IHostingStartup
    {
        public void Configure(IWebHostBuilder builder)
        {
            builder.ConfigureServices((context, services) => {
            });
        }
    }
}
而在 [Area] > [Identity] > [Pages] 目錄下,多了 [_ViewImports.cshtml] 與 [_ViewStart.cshtml] 檔案
底下將會是 [Area] > [Identity] > [Pages] > [_ViewImports.cshtml] 檔案內容
@using Microsoft.AspNetCore.Identity
@using BlazorScaffoldIdentity.Areas.Identity
@using BlazorScaffoldIdentity.Areas.Identity.Pages
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
底下將會是 [Area] > [Identity] > [Pages] > [_ViewStart.cshtml] 檔案內容
@{
    Layout = "/Pages/Shared/_Layout.cshtml";
}
在 [Area] > [Identity] > [Pages] > [Account] 目錄下,多了 [_ViewImports.cshtml] 與 [Login.cshtml] 檔案
底下將會是 [Area] > [Identity] > [Pages] > [Account] > [_ViewImports.cshtml] 檔案內容
@using BlazorScaffoldIdentity.Areas.Identity.Pages.Account
而最後這個將會是 [Area] > [Identity] > [Pages] > [Account] > [Login.cshtml] 檔案內容,這也是需要來進行客製化的 Razor Page 頁面檔案
@page
@model LoginModel

@{
    ViewData["Title"] = "Log in";
}

<h1>@ViewData["Title"]</h1>
<div class="row">
    <div class="col-md-4">
        <section>
            <form id="account" method="post">
                <h4>Use a local account to log in.</h4>
                <hr />
                <div asp-validation-summary="All" class="text-danger"></div>
                <div class="form-group">
                    <label asp-for="Input.Email"></label>
                    <input asp-for="Input.Email" class="form-control" />
                    <span asp-validation-for="Input.Email" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <label asp-for="Input.Password"></label>
                    <input asp-for="Input.Password" class="form-control" />
                    <span asp-validation-for="Input.Password" class="text-danger"></span>
                </div>
                <div class="form-group">
                    <div class="checkbox">
                        <label asp-for="Input.RememberMe">
                            <input asp-for="Input.RememberMe" />
                            @Html.DisplayNameFor(m => m.Input.RememberMe)
                        </label>
                    </div>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-primary">Log in</button>
                </div>
                <div class="form-group">
                    <p>
                        <a id="forgot-password" asp-page="./ForgotPassword">Forgot your password?</a>
                    </p>
                    <p>
                        <a asp-page="./Register" asp-route-returnUrl="@Model.ReturnUrl">Register as a new user</a>
                    </p>
                </div>
            </form>
        </section>
    </div>
    <div class="col-md-6 col-md-offset-2">
        <section>
            <h4>Use another service to log in.</h4>
            <hr />
            @{
                if ((Model.ExternalLogins?.Count ?? 0) == 0)
                {
                    <div>
                        <p>
                            There are no external authentication services configured. See <a href="https://go.microsoft.com/fwlink/?LinkID=532715">this article</a>
                            for details on setting up this ASP.NET application to support logging in via external services.
                        </p>
                    </div>
                }
                else
                {
                    <form id="external-account" asp-page="./ExternalLogin" asp-route-returnUrl="@Model.ReturnUrl" method="post" class="form-horizontal">
                        <div>
                            <p>
                                @foreach (var provider in Model.ExternalLogins)
                                {
                                    <button type="submit" class="btn btn-primary" name="provider" value="@provider.Name" title="Log in using your @provider.DisplayName account">@provider.DisplayName</button>
                                }
                            </p>
                        </div>
                    </form>
                }
            }
        </section>
    </div>
</div>

@section Scripts {
    <partial name="_ValidationScriptsPartial" />
}
對於 [Login.cshtml.cs] 檔案內容如下所示
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;

namespace BlazorScaffoldIdentity.Areas.Identity.Pages.Account
{
    [AllowAnonymous]
    public class LoginModel : PageModel
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;
        private readonly ILogger<LoginModel> _logger;

        public LoginModel(SignInManager<IdentityUser> signInManager, 
            ILogger<LoginModel> logger,
            UserManager<IdentityUser> userManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _logger = logger;
        }

        [BindProperty]
        public InputModel Input { get; set; }

        public IList<AuthenticationScheme> ExternalLogins { get; set; }

        public string ReturnUrl { get; set; }

        [TempData]
        public string ErrorMessage { get; set; }

        public class InputModel
        {
            [Required]
            [EmailAddress]
            public string Email { get; set; }

            [Required]
            [DataType(DataType.Password)]
            public string Password { get; set; }

            [Display(Name = "Remember me?")]
            public bool RememberMe { get; set; }
        }

        public async Task OnGetAsync(string returnUrl = null)
        {
            if (!string.IsNullOrEmpty(ErrorMessage))
            {
                ModelState.AddModelError(string.Empty, ErrorMessage);
            }

            returnUrl = returnUrl ?? Url.Content("~/");

            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            ReturnUrl = returnUrl;
        }

        public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return LocalRedirect(returnUrl);
                }
                if (result.RequiresTwoFactor)
                {
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToPage("./Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return Page();
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }
    }
}

將 Login 登入畫面,改成為中文版本

現在可以打開 [Login.cshtml] 這個 Razor 檔案,進行修正,改成中文版本
底下是修改後的執行結果



沒有留言:

張貼留言