Skip to content

11. 案例研究:RdvMedecins 应用程序

11.1. 问题描述

RdvMedecins 应用程序用于管理一家医疗诊所的预约。每位医生都有若干时间段(例如,从上午 8:00 到中午 12:00,每 20 分钟一个);一次预约由日期、时间段和客户(患者)组成。这是上一课中 [NestJS] 应用程序在 [ASP.NET Core MVC] 中的精确实现:相同的数据库、相同的业务规则、相同的页面、相同的翻译字典。HTML 页面由服务器使用 [Razor] 视图生成。

三种用户角色共用该应用程序:

角色
对象
可执行的操作
ADMIN
管理员([admin])
查看日程,为任何患者预约和取消预约;管理(列表、添加、编辑、删除)医生和客户
DOCTOR
医生
查看日程,为任何患者预约和取消预约
USER
客户(患者)
查看日程,但看不到其他患者的姓名;为自己预约;取消自己的预约;管理自己的账户;创建账户

主要的管理规则:

  • 不得预约过去的时间;
  • 同一个时间段每天只能被预约一次;
  • 一名患者同一时间只能有一个未到期的预约;
  • 两名医生(或两名客户)不能具有相同的姓和名,并且一个登录名只属于一个账户;
  • 有预约的医生不能被删除;客户被删除时,其预约一并删除;
  • 登录页面受到防机器人保护(验证码、限制尝试次数),并且创建客户账户需要先在该页面上通过验证码。

11.2. 使用应用程序

11.2.1. 登录页面

Image

该页面有两个按钮:登录和创建患者账户。两者都要求输入图像中显示的字符。FR / EN 按钮用于切换语言:

Image

错误(这里是验证码输入错误)显示在页面底部的浅粉色背景上:

Image

11.2.2. 日历,管理员和医生视角

登录后,管理员会进入日历页面。他们选择一位医生和一天:

Image

Image

每个时间段要么可预约(“预约”按钮),要么已被占用(患者姓名、“取消”按钮)。点击“预约”会打开一个窗口,要求填写患者信息:

Image

点击“取消”会弹出确认提示(这里是 Pélissier 医生,其导航栏不包含管理菜单):

Image

11.2.3. 患者仪表板

患者(角色 USER)进入“我的专区”:显示其即将到来的预约(可以取消),以及通往账户管理和日历的链接:

Image

在日历中,他们能看到自己的预约,但看不到其他患者的姓名。由于已经有一个未到期的预约,他们无法再预约另一个:

Image

没有预约的患者可以为自己预约一个可用的时间段:

Image

账户管理:编辑个人信息、修改密码,或删除账户(及其预约)。任何更改都需要输入当前密码:

Image

试图打开管理员专属页面的患者会收到一个错误页面:

Image

11.2.4. 管理医生和客户

管理员多出两个菜单:“医生”和“患者”:

Image

Image

添加医生的表单,提交时带有错误:

Image

与现有医生同名的姓名会被拒绝:

Image

删除客户需要确认:

Image

11.2.5. 创建客户账户

在登录页面上,“创建患者账户”按钮只有在正确输入验证码后才会打开表单:

Image

Image

11.3. 安装与运行

安装步骤已在本文档开头给出(在引言的“运行案例研究”一节中):使用 SQL 脚本创建数据库,通过 [appsettings.json] 检查连接字符串,然后在应用程序文件夹中运行 [dotnet run] 。应用程序文件夹:

rdvmedecins2-aspnetcore-mvc/
├── Auth/
│   ├── AttemptLimiterService.cs
│   ├── AuthService.cs
│   ├── CaptchaService.cs
│   ├── ConnectedUser.cs
│   ├── InvalidSessionException.cs
│   ├── JwtAuthentication.cs
│   ├── README.md
│   └── RegistrationPassService.cs
├── Business/
│   ├── BusinessException.cs
│   ├── BusinessService.cs
│   ├── Dates.cs
│   ├── IBusiness.cs
│   └── README.md
├── Config/
│   ├── AuthOptions.cs
│   ├── ProtectionOptions.cs
│   └── README.md
├── Controllers/
│   ├── AuthController.cs
│   ├── ClientsController.cs
│   ├── DoctorsController.cs
│   ├── ErrorController.cs
│   ├── LanguageController.cs
│   ├── PatientAreaController.cs
│   ├── PersonsControllerBase.cs
│   ├── README.md
│   ├── RegistrationController.cs
│   └── ScheduleController.cs
├── Data/
│   ├── RdvMedecinsDbContext.cs
│   └── README.md
├── database/
│   ├── dbrdvmedecins2.sql
│   └── README.md
├── Domain/
│   ├── DoctorDaySchedule.cs
│   ├── DoctorDaySlot.cs
│   └── README.md
├── Entities/
│   ├── AbstractEntity.cs
│   ├── Appointment.cs
│   ├── Client.cs
│   ├── Doctor.cs
│   ├── Person.cs
│   ├── README.md
│   ├── Role.cs
│   ├── Slot.cs
│   └── User.cs
├── i18n/
│   ├── en.json
│   └── fr.json
├── Models/
│   ├── Forms.cs
│   ├── README.md
│   └── ViewModels.cs
├── Properties/
│   └── launchSettings.json
├── Repositories/
│   ├── AppointmentRepository.cs
│   ├── PersonRepository.cs
│   ├── README.md
│   ├── SlotRepository.cs
│   └── UserRepository.cs
├── Views/
│   ├── Auth/
│   │   ├── _Captcha.cshtml
│   │   └── Login.cshtml
│   ├── PatientArea/
│   │   ├── Account.cshtml
│   │   └── Area.cshtml
│   ├── Persons/
│   │   ├── Form.cshtml
│   │   └── List.cshtml
│   ├── Registration/
│   │   └── Registration.cshtml
│   ├── Schedule/
│   │   ├── _Booking.cshtml
│   │   └── Schedule.cshtml
│   ├── Shared/
│   │   ├── _Confirmation.cshtml
│   │   ├── _Errors.cshtml
│   │   ├── _Flash.cshtml
│   │   ├── _Layout.cshtml
│   │   ├── _Navbar.cshtml
│   │   ├── _PersonFields.cshtml
│   │   └── Error.cshtml
│   ├── _ViewImports.cshtml
│   ├── _ViewStart.cshtml
│   └── README.md
├── Web/
│   ├── ApplicationModel.cs
│   ├── Flash.cs
│   ├── HtmlExceptionFilter.cs
│   ├── README.md
│   ├── Translator.cs
│   ├── Utils.cs
│   ├── Validation.cs
│   └── ViewPage.cs
├── wwwroot/
│   ├── css/
│   │   └── styles.css
│   ├── js/
│   │   └── app.js
│   └── lib/
│       └── bootstrap/
│           ├── css/
│           │   └── bootstrap.min.css
│           └── LICENSE
├── .gitignore
├── appsettings.Development.json
├── appsettings.json
├── Program.cs
├── RdvMedecins.csproj
└── README.md

每个文件夹都包含一个名为 [README.md] 的文件,列出其中的文件。启动时的控制台:

dotnet run
Using launch settings from Properties/launchSettings.json...
Building...
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:8081
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\course\rdvmedecins2-aspnetcore-mvc

在开发模式下(见 [Properties/launchSettings.json]),控制台还会显示 EF Core 发送到数据库的每条 SQL 命令。你还可以:

  • 使用 [dotnet watch] 启动应用程序:每当文件被修改时,它会被重新编译并重新启动;
  • 在 [Visual Studio Code] 中单步调试:安装 [C# Dev Kit] 扩展后,按 F5 键即可在调试器的控制下启动应用程序;在代码行的边栏中单击一下即可设置断点。

11.4. 应用程序架构

Image

  • [Program.cs] 配置应用程序:服务(依赖注入)、中间件(静态文件、错误页面、语言、身份验证)、控制器;
  • [Auth]:登录、JWT 令牌、角色、验证码和尝试次数限制;
  • [Controllers]:Web 层的控制器。它们都经由同一个服务 [ApplicationModel] (文件夹 [Web]),该服务将医生和客户列表保存在内存中,并把其他请求转发给业务层;
  • [Web]:Web 层的公共元素:翻译、闪现消息、验证、视图父类、异常过滤器;[Models]:表单模型和视图模型;
  • [Business]:业务规则;
  • [Repositories]:DAO 层,每个表一个类;[Data]:EF Core 的 [DbContext] 层;
  • [Entities]:EF Core 实体;[Domain]:日历对象,由业务层计算得出;
  • [Views]:[Razor] 视图;[i18n]:字典;[wwwroot]:样式表、页面脚本以及 [Bootstrap]。

后续内容将逐一说明所有文件,从底层(数据库)到上层(视图)。

11.5. 数据库

数据库 [dbrdvmedecins2] 由脚本 [database/dbrdvmedecins2.sql] 创建,其运行方式与示例 28 相同([Laragon] 中的 [HeidiSQL] 工具,或命令 [mysql -u root < database/dbrdvmedecins2.sql])。它与 [NestJS] 应用程序的脚本一字不差:两个应用程序可以使用同一个数据库,并且可以互相替换而无需做任何修改。

11.5.1. database/dbrdvmedecins2.sql

-- =========================================================================
-- Database [dbrdvmedecins2] - MySQL 8
--
-- Evolution of [dbrdvmedecins]:
--   1. the [doctors] and [clients] tables get a [user] column,
--      foreign key to users(id): every doctor and every client is
--      now also a user able to log in;
--   2. a third role appears: DOCTOR (in addition to ADMIN and USER);
--   3. the script creates a [users] row for each doctor (role DOCTOR)
--      and for each client (role USER):
--        - login        = last name in lower case
--        - password     = last name in lower case, hashed with bcrypt (10 rounds)
--        - display name = first name + last name
--
--   4. uniqueness constraints, all NAMED (the application recognizes
--      the name of the violated constraint in the MySQL error message):
--        - unq_users_login                   : a login belongs to one account only;
--        - unq_doctors_first_name_last_name  : two doctors cannot have the
--                                              same first and last names;
--        - unq_clients_first_name_last_name  : same for the clients.
--      Beware: the utf8mb4_unicode_ci collation compares regardless of
--      case and accents - "Hélène DUPONT" and "helene dupont"
--      are therefore considered identical.
--
-- The [users] table must now be created BEFORE [doctors] and [clients]
-- (they reference it), and dropped AFTER them.
-- =========================================================================

-- we start again from an empty database on each run of the script (handy in development)
CREATE DATABASE IF NOT EXISTS dbrdvmedecins2 CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
USE dbrdvmedecins2;

-- drop order: from the "child" tables to the "parent" tables
DROP TABLE IF EXISTS appointments;
DROP TABLE IF EXISTS slots;
DROP TABLE IF EXISTS clients;
DROP TABLE IF EXISTS doctors;
DROP TABLE IF EXISTS users;

-- -------------------------------------------------------------------------
-- table [users]: the users allowed to log in to the application
-- -------------------------------------------------------------------------
CREATE TABLE users (
  id       INT AUTO_INCREMENT PRIMARY KEY,
  version  INT NOT NULL DEFAULT 0,
  login    VARCHAR(30) NOT NULL,                 -- login identifier
  password VARCHAR(100) NOT NULL,                -- HASHED password (bcrypt) - never in clear
  name     VARCHAR(40) NOT NULL,                 -- name displayed once logged in
  role     VARCHAR(10) NOT NULL,                 -- 'ADMIN', 'DOCTOR' or 'USER'
  -- a login can belong to one account only
  CONSTRAINT unq_users_login UNIQUE (login)
);

-- -------------------------------------------------------------------------
-- table [doctors]: the doctors of the practice
-- -------------------------------------------------------------------------
CREATE TABLE doctors (
  id         INT AUTO_INCREMENT PRIMARY KEY,   -- primary key (technical identifier)
  version    INT NOT NULL DEFAULT 0,            -- row version number (optimistic lock)
  title      VARCHAR(5)  NOT NULL,              -- Melle, Mme, Mr
  last_name  VARCHAR(20) NOT NULL,
  first_name VARCHAR(20) NOT NULL,
  `user`     INT NOT NULL,                      -- foreign key -> users(id)
  CONSTRAINT fk_doctors_user FOREIGN KEY (`user`) REFERENCES users(id),
  -- one account per doctor, and one doctor per account
  CONSTRAINT unq_doctors_user UNIQUE (`user`),
  -- two doctors cannot have the same first and last names
  CONSTRAINT unq_doctors_first_name_last_name UNIQUE (first_name, last_name)
);

-- -------------------------------------------------------------------------
-- table [clients]: the doctors' patients
-- -------------------------------------------------------------------------
CREATE TABLE clients (
  id         INT AUTO_INCREMENT PRIMARY KEY,
  version    INT NOT NULL DEFAULT 0,
  title      VARCHAR(5)  NOT NULL,
  last_name  VARCHAR(20) NOT NULL,
  first_name VARCHAR(20) NOT NULL,
  `user`     INT NOT NULL,                      -- foreign key -> users(id)
  CONSTRAINT fk_clients_user FOREIGN KEY (`user`) REFERENCES users(id),
  -- one account per client, and one client per account
  CONSTRAINT unq_clients_user UNIQUE (`user`),
  -- two clients cannot have the same first and last names
  CONSTRAINT unq_clients_first_name_last_name UNIQUE (first_name, last_name)
);

-- -------------------------------------------------------------------------
-- table [slots]: the time slots of each doctor
-- -------------------------------------------------------------------------
CREATE TABLE slots (
  id           INT AUTO_INCREMENT PRIMARY KEY,
  version      INT NOT NULL DEFAULT 0,
  doctor_id    INT NOT NULL,                     -- foreign key -> doctors(id)
  start_hour   INT NOT NULL,                     -- start hour of the slot
  start_minute INT NOT NULL,                     -- start minute of the slot
  end_hour     INT NOT NULL,                     -- end hour of the slot
  end_minute   INT NOT NULL,                     -- end minute of the slot
  CONSTRAINT fk_slots_doctor FOREIGN KEY (doctor_id) REFERENCES doctors(id)
);

-- -------------------------------------------------------------------------
-- table [appointments]: the appointments booked by the clients
-- -------------------------------------------------------------------------
CREATE TABLE appointments (
  id         INT AUTO_INCREMENT PRIMARY KEY,
  version    INT NOT NULL DEFAULT 0,
  day        DATE NOT NULL,                      -- day of the appointment
  slot_id    INT NOT NULL,                       -- foreign key -> slots(id)
  client_id  INT NOT NULL,                       -- foreign key -> clients(id)
  CONSTRAINT fk_appointments_slot   FOREIGN KEY (slot_id)   REFERENCES slots(id),
  CONSTRAINT fk_appointments_client FOREIGN KEY (client_id) REFERENCES clients(id),
  -- the same slot, on the same day, can be booked only once
  CONSTRAINT unq1_appointments UNIQUE (day, slot_id)
);

-- =========================================================================
-- Demo data
-- =========================================================================

-- the users: passwords hashed with bcrypt (10 salt rounds)
--   admin/admin (ADMIN)
--   one DOCTOR account per doctor, one USER account per client
--   (the user/user demo account is gone: a USER account is
--   now ALWAYS a client's account, who can book and manage the account)
--   (login = password = last name in lower case)
INSERT INTO users (login, password, name, role) VALUES
  ('admin',     '$2b$10$YSNBJXXHX9mp13nPZb6YGu8M1jR6uvPwO1s2X73z0QAqBR7TOQjoq', 'Administrator',    'ADMIN'),
  -- doctors
  ('pelissier', '$2b$10$DnSDOK5ONrdMxTTr1NKCHOphR3WSp5QAyG9S9ueruw9HwlxI.16ba', 'Marie PELISSIER',  'DOCTOR'),
  ('tatou',     '$2b$10$PeovBO.gmJUKP4PglI/fwu4xtWOYSxoM5VTWjTj7uQ4wcd9P9.htS', 'Paul TATOU',       'DOCTOR'),
  ('dupont',    '$2b$10$az7wvPKC1h0EiAxXwu/PU.vYjzmB04rd5B7QnK0mvxp4niYIHVoc.', 'Sophie DUPONT',    'DOCTOR'),
  -- clients
  ('martin',    '$2b$10$GT6S5pp.WdGapFw/UmocXesbC6LEjJfZzgatCUyG9Sf4o1iBNlqZW', 'Jean MARTIN',      'USER'),
  ('durand',    '$2b$10$l2gl/zCder8E7Nh4VxGRX.0.SsO3FDiXt6YwqYq3v9nFzgC/jQCy6', 'Alice DURAND',     'USER'),
  ('bistrou',   '$2b$10$naeRp2YUU6c.QDl5itJMAum3Y5aHdUV6jwIcsbp0D.64jPG4F6E9m', 'Brigitte BISTROU', 'USER'),
  ('german',    '$2b$10$tTWxh3ROWF7NjhZOMnWDMOsZcnSWUiwwfy5C3G0.xhccTXALKyLeW', 'Luc GERMAN',       'USER');

-- the doctors: the [user] column is looked up from the login,
-- rather than assuming the values of the primary keys of [users]
INSERT INTO doctors (title, last_name, first_name, `user`) VALUES
  ('Mme',  'PELISSIER', 'Marie',  (SELECT id FROM users WHERE login = 'pelissier')),
  ('Mr',   'TATOU',     'Paul',   (SELECT id FROM users WHERE login = 'tatou')),
  ('Melle','DUPONT',    'Sophie', (SELECT id FROM users WHERE login = 'dupont'));

INSERT INTO clients (title, last_name, first_name, `user`) VALUES
  ('Mr',   'MARTIN',  'Jean',     (SELECT id FROM users WHERE login = 'martin')),
  ('Mme',  'DURAND',  'Alice',    (SELECT id FROM users WHERE login = 'durand')),
  ('Melle','BISTROU', 'Brigitte', (SELECT id FROM users WHERE login = 'bistrou')),
  ('Mr',   'GERMAN',  'Luc',      (SELECT id FROM users WHERE login = 'german'));

-- slots of doctor PELISSIER (doctor_id = 1): from 8:00 to 12:00 in 20-minute steps
INSERT INTO slots (doctor_id, start_hour, start_minute, end_hour, end_minute) VALUES
  (1, 8, 0, 8, 20), (1, 8, 20, 8, 40), (1, 8, 40, 9, 0),
  (1, 9, 0, 9, 20), (1, 9, 20, 9, 40), (1, 9, 40, 10, 0),
  (1, 10, 0, 10, 20), (1, 10, 20, 10, 40), (1, 10, 40, 11, 0),
  (1, 11, 0, 11, 20), (1, 11, 20, 11, 40), (1, 11, 40, 12, 0);

-- slots of doctor TATOU (doctor_id = 2): from 14:00 to 18:00 in 20-minute steps
INSERT INTO slots (doctor_id, start_hour, start_minute, end_hour, end_minute) VALUES
  (2, 14, 0, 14, 20), (2, 14, 20, 14, 40), (2, 14, 40, 15, 0),
  (2, 15, 0, 15, 20), (2, 15, 20, 15, 40), (2, 15, 40, 16, 0),
  (2, 16, 0, 16, 20), (2, 16, 20, 16, 40), (2, 16, 40, 17, 0),
  (2, 17, 0, 17, 20), (2, 17, 20, 17, 40), (2, 17, 40, 18, 0);

-- an appointment already booked, to see an occupied slot right away in the schedule
INSERT INTO appointments (day, slot_id, client_id) VALUES
  (CURDATE(), 2, 3);

让我们逐段看看这个脚本:

  • 第 30 行:如果数据库尚不存在则创建,使用字符集 [utf8mb4] 和排序规则 [utf8mb4_unicode_ci],与示例 28 相同:字符串比较不区分大小写并忽略重音。这同样适用于唯一性约束:[Hélène DUPONT] 和 [helene dupont] 对 [MySQL] 而言是同一个人的两个实例;
  • 第 34–38 行:脚本每次执行都从空数据库开始。表按从“子”表到“父”表的顺序删除:被外键引用的表(例如 [users],被 [doctors] and [clients]引用)只要还有其他表引用它,就无法删除。创建表时则按相反的顺序;
  • 第 43–52 行:用户账户。每个表都以主键 [id](由数据库分配,[AUTO_INCREMENT])和列 [version] 开头,该列在创建行时设为 0;
  • 第 46–49 行:登录名、密码、登录后的显示名称和角色([ADMIN]、[DOCTOR], 或 [USER])。[password] 列从不包含密码本身,而是包含其 [bcrypt] 哈希(见示例 25):60 个字符,列宽由此而来;
  • 第 51 行:一个登录名只属于一个账户。与示例 28 一样,该约束是具名的:当 [MySQL] 拒绝某次写入操作时,其错误消息会指明被违反的约束的名称,业务层据此选择要显示的消息(见 [Business/BusinessService.cs]);
  • 第 57–69 行:医生:头衔、姓、名;
  • 第 59 行:列 [version] 用于乐观锁 (见示例 28):每次修改该行时它都会递增,这样就能检测另一个用户是否在该行被读取与被写入之间修改了它。与示例 28 一样,应用程序负责递增该值(见下文的 [DbContext]);
  • 第 63–64 行:每位医生都有一个账户:列 [user] 是引用 外键 [users(id)] 的列。数据库会拒绝不指向任何账户的值,并拒绝删除仍被医生引用的账户。由于 [user] 是 [MySQL] 中的保留字,列名用反引号括起来;
  • 第 66 行:一个账户只属于一位医生:[doctors] 与 [users] 之间是“一对一”关系;
  • 第 68 行:两位医生不能具有相同的姓和名。该约束作用于这一对列:如果名不同,两位医生可以姓相同;
  • 第 74–86 行:客户(患者),遵循同样的模式:每个客户一个账户(外键 [fk_clients_user],唯一性约束 [unq_clients_user]);任何两个客户不能具有相同的姓和名;
  • 第 91–100 行:每位医生的时间段(外键 [doctor_id]):开始的小时和分钟、结束的小时和分钟。时间段没有日期;它每天重复;
  • 第 105–115 行:预约:一个日期(类型 [DATE],不含时间)、一个时间段,以及一个客户,由两个外键标识;
  • 第 114 行:同一个时间段每天只能被预约一次。数据库本身强制执行这条规则:如果两个用户同时预约同一个时间段,无论应用程序刚才验证了什么,第二条 [INSERT] 语句都会被拒绝;
  • 第 127–137 行:演示账户:管理员、三位医生(角色 [DOCTOR])和四位客户(角色 [USER])。每个用户的密码就是其登录名([admin] / [admin]、[pelissier] / [pelissier]……)。哈希以 [$2b$10$] 开头:算法为 [bcrypt],成本为 10(见示例 25);应用程序的库 [BCrypt.Net-Next] 知道如何验证它们;
  • 第 141–144 行:每位医生的 [user] 列通过基于登录名的子查询 获取,而不是假定数据库分配给账户的标识符;
  • 第 146–150 行:客户以同样的方式处理;
  • 第 153–157 行:为 PELISSIER 医生提供十二个 20 分钟的时间段,从上午 8:00 到中午 12:00。这里医生的 ID(1)是硬编码的:表 [doctors] 刚刚创建,因此其 ID 从 1 开始;
  • 第 160–164 行:为 TATOU 医生提供十二个时间段,从下午 2:00 到下午 6:00。DUPONT 医生没有时间段:他的日程是空的;
  • 第 167–168 行:已经为 Brigitte BISTROU(客户 3 号)在 PELISSIER 医生的第二个时间段(上午 8:20)安排了一次预约。[CURDATE()] 是运行脚本的日期:因此首次登录时,今天的日历会显示一个已被预约的时间段。

11.6. 项目配置

11.6.1. RdvMedecins.csproj

<!--
  =========================================================================
  RdvMedecins.csproj - the project file (the equivalent of package.json).

  Microsoft.NET.Sdk.Web: the SDK of ASP.NET Core applications. On its own it
  brings the whole web framework (MVC, Razor views, authentication,
  localization, static files...): only the libraries
  EXTERNAL to the framework are listed below (PackageReference), and
  downloaded from nuget.org by [dotnet restore] / [dotnet build].
  =========================================================================
-->
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <!-- .NET 10,LTS 版本(长期支持) -->
    <TargetFramework>net10.0</TargetFramework>
    <!-- "nullable" reference types: the compiler reports the risks of
         NullReferenceException (the equivalent of strictNullChecks in TypeScript) -->
    <Nullable>enable</Nullable>
    <!-- 隐式 using:System、System.Linq、System.Threading.Tasks…… -->
    <ImplicitUsings>enable</ImplicitUsings>
    <RootNamespace>RdvMedecins</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <!-- Entity Framework Core + its MySQL / MariaDB provider.
         Pomelo itself pulls Microsoft.EntityFrameworkCore (and MySqlConnector,
         the ADO.NET driver) in the version that matches it. -->
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="9.0.0" />
    <!-- JWT 令牌身份验证(读取并验证令牌) -->
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.0" />
    <!-- password hashing (bcrypt), compatible with the
         $2b$ hashes of the SQL script -->
    <PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
  </ItemGroup>

  <ItemGroup>
    <!-- the translation dictionaries are read at startup. The Web SDK
         already puts all .json files among the files to publish (Content):
         we simply specify to always copy them (dotnet publish) -->
    <Content Update="i18n\*.json" CopyToPublishDirectory="PreserveNewest" />
    <!-- SQL 脚本无需发布 -->
    <Content Remove="database\**" />
    <None Include="database\**" />
  </ItemGroup>

</Project>

让我们逐段看看这个文件:

  • 第 12 行:Web 应用程序的 SDK,与所有示例相同(见引言);
  • 第 14–23 行:示例中位于共享文件 [examples/Directory.Build.props] 里的设置:[.NET] 10、“可为 null”的引用类型、隐式 [using]。案例研究是一个独立的项目:这些设置由它自己写出。[RootNamespace] 是项目的根命名空间,即 [Visual Studio Code] 为新文件建议使用的命名空间;
  • 第 29 行:EF Core 的 [MySQL] 提供程序,它包含 EF Core 和 [MySqlConnector] 驱动程序(见示例 28);
  • 第 31–34 行:两个身份验证包,已在第 8 章中使用过:JWT 令牌验证和密码哈希;
  • 第 41 行:翻译字典 [i18n/*.json] 在启动时从磁盘读取。为生产服务器准备应用程序时(命令 [dotnet publish]),必须将它们一并复制:这正是 [CopyToPublishDirectory] 所做的;
  • 第 43–44 行:SQL 脚本不是应用程序文件;它被排除在发布的文件之外,如示例 28 所示。

11.6.2. appsettings.json

文件 [appsettings.json] 的作用与 [.env] 文件在 [NestJS] 应用程序中的作用相同。有一个重要差别:[.env] 文件从不共享,而名为 [.env.example] 的文件充当它的模板。这里,[appsettings.json] 是项目的一部分;与具体机器相关的值(例如密码)可以通过其他方式提供,而无需修改它(见下文)。

// =========================================================================
// appsettings.json:应用程序的配置(相当于 NestJS 项目的
// .env 文件)。ASP.NET Core 允许
// 在这个 JSON 文件中写注释。
//
// 敏感值(MySQL 密码、JWT 密钥)可以
// 在不修改此文件的情况下替换:环境变量或
// “用户机密”(见 README.md,Configuration 一节)。
// =========================================================================
{
  // 监听端口。JSON 服务器已经监听 8080:我们选择另一个
  // 端口,以便两者能同时运行。
  "Urls": "http://localhost:8081",

  // 连接到 MySQL 数据库 [dbrdvmedecins2](脚本:database/dbrdvmedecins2.sql)
  "ConnectionStrings": {
    "RdvMedecins": "Server=localhost;Port=3306;Database=dbrdvmedecins2;User=root;Password=;"
  },
  "MySql": {
    // 服务器版本,使 EF Core 生成正确的 SQL 方言:
    // MySQL 8 用 "8.0.0-mysql",MariaDB 10.11 用 "10.11.0-mariadb"……
    "ServerVersion": "8.0.0-mysql"
  },

  // 身份验证(见 Auth/)
  "Auth": {
    // JWT 令牌的密钥:至少 32 个字符(HMAC-SHA256)。
    // 在生产环境中务必更换(使用较长的随机字符串)。
    "JwtSecret": "change-me-to-a-long-random-string",
    // 令牌的有效时长,单位为秒(7200 秒 = 2 小时);承载令牌的 Cookie
    // 具有相同的生存期
    "JwtExpiresInSeconds": 7200,
    // 生产环境中为 true(站点通过 HTTPS 提供):此时身份验证 Cookie
    // 绝不会通过未加密的连接发送
    "CookieSecure": false
  },

  // 防范机器人(见 Auth/AttemptLimiterService.cs)
  "Protection": {
    // 登录:同一 IP 地址上同一登录名允许的失败次数……
    "LoginMaxFailures": 5,
    // ……超过后封锁该时长(如果同一 IP 地址累计的失败次数达到其 5 倍,
    // 则整个 IP 地址也会被封锁,所有登录名合计)
    "LoginBlockMinutes": 15,
    // 创建客户端账户:每个 IP 地址每小时最多创建这么多个账户。
    // 在教室里,所有计算机往往通过
    // 同一个地址出网:必要时请调大。
    "RegistrationMaxPerHour": 10
  },

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.EntityFrameworkCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

让我们逐段看看这个文件:

  • 第 1–9 行:与标准 JSON 不同,[ASP.NET Core] 允许在其配置文件中使用注释;
  • 第 13 行:监听的地址和端口。示例监听 5000 端口,即默认端口;应用程序监听 8081 端口,与 [NestJS] 版本相同;
  • 第 16–18 行:到 [dbrdvmedecins2] 数据库的连接字符串,使用 [Laragon] 的默认值(用户名 [root],无密码);见示例 28;
  • 第 19–23 行:服务器版本,它告诉提供程序 [Pomelo] 应生成哪种 SQL 方言(见示例 28);
  • 第 26–36 行:身份验证节:为令牌签名的密钥(至少 32 个字符;在生产环境中必须替换)、令牌的生存期(两小时),以及携带令牌的 Cookie 的 [Secure] 选项。在生产环境中,站点通过 HTTPS 提供服务,Cookie 绝不能通过未加密的连接传输:该选项设为 [true];
  • 第 39–49 行:机器人防护阈值(见示例 27):允许的登录失败次数以及由此产生的封锁时长;同一 IP 地址每小时创建客户账户的数量;
  • 第 51–57 行:日志级别(见引言)。EF Core 的消息仅从 [Warning] 级别开始显示:属于 [Information] 级别的 SQL 命令不会出现(见示例 28);
  • 第 58 行:接受所有域名。

节 [Auth] 和 [Protection] 被解释为带类型的类(见下文的 [Config/AuthOptions.cs])。每个值由其路径指定,层级之间以 [:] 分隔:[Auth:JwtSecret]、[ConnectionStrings:RdvMedecins]、[MySql:ServerVersion]。[ASP.NET Core] 从多个依次排列的来源读取配置,后面的来源可以覆盖前面来源的值:[appsettings.json],然后是 [appsettings.{environment}.json] (见下一个文件),然后在开发环境中是“用户机密”(存储在项目之外、用户配置文件中的值),再然后是环境变量,最后是命令行参数。因此,密码可以通过环境变量提供,其中 [:] 写成 [__]:

export ConnectionStrings__RdvMedecins="Server=localhost;Port=3306;Database=dbrdvmedecins2;User=root;Password=myPassword;"

应用程序的 [README.md] 文件详细说明了这些选项。

11.6.3. appsettings.Development.json

// 开发环境下对 appsettings.json 的覆盖(ASPNETCORE_ENVIRONMENT=
// Development,见 Properties/launchSettings.json):我们在
// 控制台中显示 EF Core 生成的 SQL 查询,就像 TypeORM 的
// logging: true 选项那样。
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "Microsoft.EntityFrameworkCore.Database.Command": "Information"
    }
  }
}
  • 第 10 行:[ASP.NET Core] 知道应用程序运行所处的环境 :[Development]、[Production]……它从环境变量 [ASPNETCORE_ENVIRONMENT] 中读取该信息(见下一个文件);否则使用 [Production]。在 [appsettings.json] 之后,它读取文件 [appsettings.{environment}.json](如果存在),并将两者合并:第二个文件中存在的键会替换第一个文件中的键,其余的键予以保留。因此在开发期间,我们为类别 [Information] 添加级别 [Microsoft.EntityFrameworkCore.Database.Command]:更具体的规则优先于 [appsettings.json] 中更一般的规则([Warning] ,适用于任何 [Microsoft.EntityFrameworkCore]),于是发送到数据库的每条 SQL 命令都会显示在控制台中。这相当于 [logging] 选项在 [TypeORM] 中的对应项,[NestJS] 版本在非生产环境中启用了它。所有其他值(连接、身份验证等)与 [appsettings.json] 中的保持一致。

11.6.4. Properties/launchSettings.json

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:8081",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

此文件仅在开发期间由 [dotnet run]、[dotnet watch] 和 [Visual Studio Code] 使用,不会被发布。下面逐项说明:

  • 第 3–4 行:启动配置文件 描述启动应用程序的一种方式。这里只有一个;[dotnet run] 使用第一个;
  • 第 5 行:应用程序直接启动,使用其自带的 Web 服务器;
  • 第 6–7 行:[dotnet run] 显示其编译消息,应用程序就绪后浏览器会打开该应用程序;
  • 第 8 行:监听地址,与 [Urls] 键(来自 [appsettings.json])相同。通过此配置文件启动时,应用程序使用该地址;在配置文件之外启动时(例如发布之后),则使用 [appsettings.json] 中的地址;
  • 第 9–10 行:传递给应用程序的环境变量。[ASPNETCORE_ENVIRONMENT=Development] 设置环境:[appsettings.Development.json] 会被读取,并显示 SQL 命令。在生产服务器上,如果没有此文件或此变量,环境为 [Production]。

11.6.5. Config/AuthOptions.cs

// =========================================================================
// Config/AuthOptions.cs
// -------------------------------------------------------------------------
// appsettings.json 的 "Auth" 节,表示为强类型类。
//
// 这就是 ASP.NET Core 的“选项模式”:在
// Program.cs 中,builder.Services.Configure<AuthOptions>(...) 将该节
// 绑定到类;需要它的类随后通过依赖注入
// 接收 IOptions<AuthOptions>。这样我们就避免了到处读取字符串,
// 就像 process.env.JWT_SECRET 那样。
// =========================================================================

namespace RdvMedecins.Config;

public class AuthOptions
{
    public const string Section = "Auth";

    // 用于签名 / 验证 JWT 令牌的密钥。HMAC-SHA256
    // 算法要求密钥至少 256 位,即 32 字节。
    public string JwtSecret { get; set; } = "";

    // 令牌的有效时长,单位为秒;承载它的 Cookie
    // 具有相同的生存期
    public int JwtExpiresInSeconds { get; set; } = 7200;

    // 生产环境(HTTPS)中为 true:身份验证 Cookie 绝不会
    // 通过未加密的连接发送
    public bool CookieSecure { get; set; }
}

下面对这段代码进行说明:

  • 第 15 行:[Auth] 节,来自 [appsettings.json],以普通类的形式表示:每个键对应一个同名属性。这就是 选项模式 ([options pattern]),用于 [ASP.NET Core]。在 [Program.cs] 中,[Configure<AuthOptions>(...)] 将 该节与该类关联:框架创建一个 [AuthOptions] 对象,并用该节的值填充其属性,同时将它们转换为正确的类型(["7200"] 变为整数 7200,[false] 变为 布尔值 [false])。需要它的类通过依赖注入以 ***[IOptions<AuthOptions>] 的形式接收它,其 ***[Value] 属性就是已填充的对象:[Auth/AuthService.cs] 正是这样做的,它有参数 [IOptions<AuthOptions> options] 和字段 [auth = options.Value]。这样就避免了到处读取字符串,就像 [process.env.JWT_SECRET] 在 [NestJS] 版本中所做的那样:键名由编译器验证,值也已完成转换;
  • 第 17 行:节名称,只写一次;
  • 第 21–29 行:该节的三个值。默认值([7200],布尔值为 [false])是配置中缺少该键时所使用的值。

11.6.6. Config/ProtectionOptions.cs

// =========================================================================
// Config/ProtectionOptions.cs
// -------------------------------------------------------------------------
// appsettings.json 的 "Protection" 节:防范机器人的
// 保护阈值(见 Auth/AttemptLimiterService.cs)。
// =========================================================================

namespace RdvMedecins.Config;

public class ProtectionOptions
{
    public const string Section = "Protection";

    // 登录:同一 IP 地址上同一登录名允许的失败次数(验证码或密码错误),
    // 超过后该组合被封锁……
    public int LoginMaxFailures { get; set; } = 5;

    // ……封锁该时长(如果同一 IP 地址累计的失败次数达到其 5 倍,
    // 则该 IP 地址也会被封锁,所有登录名合计)
    public int LoginBlockMinutes { get; set; } = 15;

    // 创建客户端账户:同一 IP 地址每小时最多创建的账户数。
    // 在教室里,所有计算机往往
    // 通过同一个地址出网:必要时请调大。
    public int RegistrationMaxPerHour { get; set; } = 10;
}
  • 第 10–25 行:[Protection] 节,来自 [appsettings.json],遵循相同的模式。它以 [IOptions<ProtectionOptions>] 的形式被注入到 [Auth/AttemptLimiterService.cs] 中,后者从中读取其阈值。

11.7. 应用程序启动

11.7.1. Program.cs

文件 [Program.cs] 同时承担了 [main.ts] (启动、中间件)和 [app.module.ts] (由哪个服务提供什么)在 [NestJS] 版本中的角色。它遵循所有示例的结构:先注册服务,再构建中间件管道。我们将其分段讲解。

11.7.1.1. 配置

// =========================================================================
// Program.cs
// -------------------------------------------------------------------------
// 应用程序的入口点:相当于 main.ts
// (启动、中间件)和 app.module.ts(谁提供什么)二者之和。
//
// 两个阶段,始终按此顺序:
//
//   1. builder.Services... :我们在依赖注入
//      容器中注册服务(相当于 NestJS 模块的 "providers")。
//      每个服务都有一个生命周期:
//        - Singleton:整个应用程序一个实例;
//        - Scoped:每个 HTTP 请求一个实例(DbContext 以及所有
//                      使用它的对象);
//        - Transient:每次请求时都是一个新实例。
//
//   2. app.Use... :我们构建中间件管道,每个
//      请求都按声明的顺序依次经过它们。
// =========================================================================

using System.Globalization;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using Microsoft.AspNetCore.Localization;
using Microsoft.EntityFrameworkCore;
using RdvMedecins.Auth;
using RdvMedecins.Config;
using RdvMedecins.Data;
using RdvMedecins.Business;
using RdvMedecins.Repositories;
using RdvMedecins.Web;

var builder = WebApplication.CreateBuilder(args);

// =========================================================================
// 1. 服务
// =========================================================================

// 类型化配置(appsettings.json 的各节,见 Config/)
builder.Services.Configure<AuthOptions>(builder.Configuration.GetSection(AuthOptions.Section));
builder.Services.Configure<ProtectionOptions>(builder.Configuration.GetSection(ProtectionOptions.Section));
var authOptions = builder.Configuration.GetSection(AuthOptions.Section).Get<AuthOptions>() ?? new AuthOptions();
  • 第 21–31 行:所使用的命名空间,除隐式的 [using] 之外:包括框架的命名空间(本地化、EF Core、HTML 编码)以及应用程序的命名空间(每个文件夹一个);
  • 第 33 行:应用程序构建器,与所有示例相同。它已读取配置([appsettings.json]、[appsettings.Development.json]、环境变量等),可通过 [builder.Configuration] 访问;
  • 第 40–41 行:选项模式(参见 [Config/AuthOptions.cs]):每个节与其类关联。[GetSection("Auth")] 指定该节;[Configure<T>] 注册相应的服务 [IOptions<T>],身份验证服务将通过注入接收它;
  • 第 42 行:同一个节,这次直接读取为对象([Get<AuthOptions>()]),如果该节缺失,则得到带默认值的对象。[JwtBearer] (见下文)的配置在服务注册期间就立即需要密钥:此时依赖注入容器尚未构建,因此无法注入任何 [IOptions<AuthOptions>]。

11.7.1.2. 数据库、DAO 层和业务层

// Entity Framework Core:DbContext,每个请求一个(Scoped)。
// UseMySql:用于 MySQL / MariaDB 的 Pomelo 提供程序。服务器
// 版本告诉它应生成哪种 SQL 方言。
var connectionString = builder.Configuration.GetConnectionString("RdvMedecins")
    ?? throw new InvalidOperationException("ConnectionStrings:RdvMedecins missing from appsettings.json");
var serverVersion = ServerVersion.Parse(builder.Configuration["MySql:ServerVersion"] ?? "8.0.0-mysql");
builder.Services.AddDbContext<RdvMedecinsDbContext>(options => options.UseMySql(connectionString, serverVersion));

// DAO 层和业务层:Scoped,与它们所依赖的 DbContext 一致
// (服务的生存期绝不能比其依赖项更长)
builder.Services.AddScoped<DoctorRepository>();
builder.Services.AddScoped<ClientRepository>();
builder.Services.AddScoped<SlotRepository>();
builder.Services.AddScoped<AppointmentRepository>();
builder.Services.AddScoped<UserRepository>();
// “请求 IBusiness 时,提供 BusinessService”(NestJS:
// { provide: BUSINESS_TOKEN, useClass: BusinessService })。在 C# 中,接口
// 本身就充当注入令牌。
builder.Services.AddScoped<IBusiness, BusinessService>();

// 缓存(单例)及其外观(scoped),见 Web/ApplicationModel.cs
builder.Services.AddSingleton<ListCache>();
builder.Services.AddScoped<ApplicationModel>();
  • 第 4–5 行:连接字符串,与示例 28 中相同。运算符 [??] 在左侧的值不为 [null] 时返回左侧的值,否则返回右侧的值:如果缺少该键,应用程序会立即停止并显示说明缺少什么的消息,而不是在第一个请求时返回一个晦涩的错误;
  • 第 6 行:[MySQL] 服务器版本,如果缺少该键则使用默认值;
  • 第 7 行:应用程序的 [DbContext] (参见 [Data/RdvMedecinsDbContext.cs]),每个请求一个([Scoped]),使用 [MySQL] 提供程序(参见示例 28);
  • 第 11–15 行:DAO 层:每个表一个类([users] 除外,其仓库用于身份验证)。它是 [Scoped],与它所使用的 [DbContext] 一样。服务的生命周期绝不能超过它的依赖项:[Singleton] 的 DAO 会无限期地保留第一个请求的 [DbContext] ,尽管它在该请求结束时已被销毁(参见第 6 章);
  • 第 19 行:业务层。[AddScoped<IBusiness, BusinessService>()] 的含义是:“当某个服务请求 [IBusiness] 时,向它提供一个 [BusinessService]”。使用业务层的类依赖于接口,而不是类:我们可以替换实现(例如换成测试版本),只需 修改这一行。[NestJS] 版本为此需要一个令牌([BUSINESS_TOKEN]),因为 [TypeScript] 接口在编译时会消失;而在 [C#] 中,接口本身就充当令牌;
  • 第 22–23 行:Web 层缓存(医生列表和客户列表)具有应用程序级作用域:[Singleton],即由所有请求共享的单个实例(参见示例 23)。所有控制器都经由其外观 [ApplicationModel],它使用业务层,因此是 [Scoped]。缓存本身不依赖任何其他内容,可以比外观存活更久。

11.7.1.3. 身份验证、翻译和编码:HTML

// 身份验证
builder.Services.AddScoped<AuthService>();
builder.Services.AddSingleton<CaptchaService>(); // 待处理的验证码:在内存中
builder.Services.AddSingleton<AttemptLimiterService>(); // 计数器:在内存中
builder.Services.AddSingleton<RegistrationPassService>(); // 通行证:在内存中
builder.Services.AddJwtAuthentication(authOptions); // 见 Auth/JwtAuthentication.cs
builder.Services.AddAuthorization();

// 翻译
builder.Services.AddSingleton<Translator>();

// Razor HTML 编码器。默认情况下,它会把每个非 ASCII
// 字符替换为实体("é" -> "&#xE9;"):页面显示正常,
// 但其源代码变得难以阅读。我们允许它原样输出
// 所有语言的字符;而 < > & " ' 始终会被转义。
builder.Services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
  • 第 2 行:登录服务(验证用户名和密码,生成令牌;参见示例 25)。它使用账户仓库,因此是 [Scoped];
  • 第 3–5 行:待处理的验证码(CAPTCHA)、失败计数器和账户创建口令(参见示例 27)。这些数据保存在内存中,且对所有请求必须相同:这三个服务都是 [Singleton]。缺点是:每次服务器重启时它们都会丢失;
  • 第 6 行:[JwtBearer] 的配置(从 Cookie 中读取令牌、重定向到登录页等),如示例 25 所示。它存放在 扩展方法 中,该方法扩展 [IServiceCollection] (参见 [Auth/JwtAuthentication.cs]),其调用方式与框架方法相同,从而减轻了 [Program.cs] 的负担;
  • 第 7 行:授权服务,由 [[Authorize]] 和中间件 [UseAuthorization] 使用;
  • 第 10 行:翻译服务,它一次性读取全部字典(参见示例 22);
  • 第 16 行:来自 [Razor] 的 HTML 编码器允许所有语言的字符通过,与示例 15 相同。

11.7.1.4. MVC 及其选项

// MVC:控制器 + Razor 视图
builder.Services.AddControllersWithViews(options =>
{
    // InvalidSessionException -> 返回登录页面
    options.Filters.Add<HtmlExceptionFilter>();

    // 启用“可为空”类型后,MVC 会自动把(不可为空的)
    // string 属性视为必填。我们更愿意自己
    // 用 [Required] 显式声明(见 Models/Forms.cs)。
    options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true;

    // 绑定错误的消息(在期望数字的地方给了文本:
    // version="abc"……)同样是翻译键
    var messages = options.ModelBindingMessageProvider;
    messages.SetValueMustNotBeNullAccessor(_ => "ERRORS.INVALID_FORM");
    messages.SetAttemptedValueIsInvalidAccessor((_, _) => "ERRORS.INVALID_FORM");
    messages.SetValueIsInvalidAccessor(_ => "ERRORS.INVALID_FORM");
    messages.SetValueMustBeANumberAccessor(_ => "ERRORS.INVALID_FORM");
    messages.SetUnknownValueIsInvalidAccessor(_ => "ERRORS.INVALID_FORM");
    messages.SetNonPropertyAttemptedValueIsInvalidAccessor(_ => "ERRORS.INVALID_FORM");
    messages.SetNonPropertyUnknownValueIsInvalidAccessor(() => "ERRORS.INVALID_FORM");
    messages.SetNonPropertyValueMustBeANumberAccessor(() => "ERRORS.INVALID_FORM");
    messages.SetMissingBindRequiredValueAccessor(_ => "ERRORS.INVALID_FORM");
    messages.SetMissingKeyOrValueAccessor(() => "ERRORS.INVALID_FORM");
    messages.SetMissingRequestBodyRequiredValueAccessor(() => "ERRORS.INVALID_FORM");
});
  • 第 2 行:[Razor] 控制器和视图。作为参数传递的函数用于设置 MVC 的选项;
  • 第 5 行:一个全局异常过滤器(参见示例 24),适用于所有操作。它只处理一种情况:[InvalidSessionException] (令牌有效,但它所指向的账户此后已被删除)会导向登录页。其他异常继续沿其路径传递到 [UseExceptionHandler] 中间件(见下文);
  • 第 10 行:“可为空”类型的一个陷阱。启用后,MVC 会将模型的(不可为空的)[string] 属性视为必填,就如同它带有 [[Required]] 特性一样,并给出我们看不懂的英文错误消息。此选项取消了这一默认行为:只有显式带有 [[Required]] 特性时,字段才是必填的,并使用我们自己的消息(参见 [Models/Forms.cs]);
  • 第 14–25 行:绑定错误消息(参见示例 19):期望数字的地方出现了文本([version=abc])、缺少值等。示例 19 只重新定义了其中两条,且是英文的;本案例研究重新定义了全部消息,并且每条都返回同一个翻译键,即 [ERRORS.INVALID_FORM],而不是文本:消息在显示时按用户的语言翻译。字符 [_] 表示未使用的参数(字段名、输入的值):无论哪个字段,消息都相同。应用程序自己的表单绝不应出现这些错误:它们表明请求是手工构造的。

11.7.1.5. 加载缓存

var app = builder.Build();

// =========================================================================
// 缓存加载(医生和客户端列表)。Scoped 服务
// 只存在于某个“作用域”内(通常是一个请求):我们为此次加载
// 创建一个作用域。数据库不可达 -> 应用程序
// 在此处停止,并在控制台中输出 EF Core 异常。
// =========================================================================
using (var scope = app.Services.CreateScope())
{
    await scope.ServiceProvider.GetRequiredService<ApplicationModel>().LoadAsync();
}
  • 第 1 行:应用程序构建完成。依赖注入容器现已创建:不能再注册服务,但可以获取服务;
  • 第 9–12 行:在服务器开始监听之前,医生列表和客户列表被加载到缓存中。[ApplicationModel] 是一个 [Scoped] 服务:它只能在 作用域内创建,而在请求之外没有作用域。[CreateScope()] 创建一个作用域;[GetRequiredService<ApplicationModel>()] 从中获取该服务(连同它所依赖的业务层、仓库和 [DbContext] ),而 [LoadAsync()] 填充缓存,缓存是 [Singleton] ,因此在作用域结束后依然存在。[using] 语句在代码块结束时销毁作用域,连同其中的 [DbContext] 一起销毁。如果数据库无法访问,EF Core 异常不会被捕获:应用程序终止,并在控制台中显示错误消息。这是连接字符串有误或 [MySQL] 服务器已停止的第一个征兆。

11.7.1.6. 中间件管道

// =========================================================================
// 2. 中间件管道:顺序很重要
// =========================================================================

// 错误变为 HTML 页面(见 Web/HtmlExceptionFilter.cs):
// 未处理的异常 -> 500 页面(异常会写入日志);
// 没有内容的 400 / 403 / 404 响应 -> 对应的错误页面
app.UseExceptionHandler("/error/500");
app.UseStatusCodePagesWithReExecute("/error/{0}");

// wwwroot/ 文件夹的静态文件:/css/...、/js/...、/lib/bootstrap/...
app.UseStaticFiles();

// 每个请求的语言:从 Cookie 读取(见 LanguageController),
// 默认为英语。它设置 CultureInfo.CurrentCulture(日期格式)
// 和 CultureInfo.CurrentUICulture(文本语言,见 Web/Translator.cs)。
var cultures = Translator.Languages.Select(l => new CultureInfo(l)).ToList();
var localization = new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture(Translator.DefaultLanguage),
    SupportedCultures = cultures,
    SupportedUICultures = cultures,
};
// 只有 Cookie 起决定作用(不看浏览器语言,也不看 URL 参数)
localization.RequestCultureProviders = [new CookieRequestCultureProvider()];
app.UseRequestLocalization(localization);

// 路由,然后身份验证(是谁?-> HttpContext.User,来自
// 令牌),再然后授权(是否允许?-> [Authorize])
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

// 控制器,其路由由特性声明([HttpGet("...")])
app.MapControllers();

app.Run();

每个请求按照中间件声明的顺序依次经过各个中间件组件(参见第 7 章):因此这个顺序很重要。

  • 第 8 行:第一个中间件包裹所有其他中间件。如果某个异常没有被任何人处理(编程错误、数据库变得不可访问等),它会记录该异常,并以地址 [/error/500] 重新执行请求:用户看到的是应用程序错误页面,而不是技术性消息(参见第 7 章);
  • 第 9 行:空的错误响应(400、403、404)以同样的方式转换为页面,通过 [/error/{code}] 操作,该操作属于 [ErrorController] 控制器(参见示例 24 和 26)。重新执行的请求会再次经过后面的中间件:因此错误页面会被渲染,并能识别已登录的用户;
  • 第 12 行:[wwwroot] 文件夹中的静态文件(参见示例 15):样式表、页面脚本和 [Bootstrap],它存放在 [wwwroot/lib/bootstrap] 中。由于放在管道的前面,该中间件响应文件请求时无需经过本地化或身份验证;
  • 第 17–23 行:本地化配置,与示例 22 相同。支持的语言和默认语言来自翻译服务([Translator.Languages], [Translator.DefaultLanguage]):它们只在一处定义;
  • 第 25 行:只有由 [LanguageController] 设置的 Cookie 决定语言(参见示例 22)。语法 [[...]] 是一个集合表达式:这里是只含一个元素的列表;
  • 第 26 行:本地化中间件,为每个请求设置语言;
  • 第 30–32 行:路由,然后是身份验证,再然后是授权。路由根据通过特性声明的路由选择将处理请求的操作。示例中没有调用它:[WebApplication] 因此会自动将其添加到管道的开头。显式调用它可以让顺序一目了然:授权必须在路由之后,因为被选中的操作才带有需要验证的 [[Authorize]] 特性;也必须在身份验证之后,身份验证根据令牌确定用户是谁(参见示例 25);
  • 第 35 行:控制器及其路由,通过特性声明([[Route("schedule")]] 等);
  • 第 37 行:服务器启动,并在 8081 端口等待请求。

11.8. 实体

EF Core 实体对应于数据库表和 [C#] 类(参见示例 28)。它们一一复刻了 [TypeORM] 实体(来自 [NestJS] 版本):特性 [[Table]]、[[Column]]、[[Key]]、[[ForeignKey]] 相当于装饰器 [@Entity]、[@Column]、[@PrimaryGeneratedColumn] 和 [@JoinColumn]。数据库不是由 EF Core 创建的,而是由 SQL 脚本 [database/dbrdvmedecins2.sql] 创建:实体只需准确描述已存在的表即可。

11.8.1. Entities/AbstractEntity.cs

// =========================================================================
// Entities/AbstractEntity.cs
// -------------------------------------------------------------------------
// 所有实体共有的两个字段:标识符 [id] 和
// 版本号 [version](乐观锁)。
//
// 与 TypeORM(以及 JPA 中的 @MappedSuperclass)一样,只需让一个
// 抽象类作为实体类的父类:EF Core 不会为它创建表,
// 而是把它的属性添加到子类的表中。
//
// [Key]、[Column]……这些特性来自标准命名空间
// System.ComponentModel.DataAnnotations:EF Core 读取它们来构建
// 自己的“模型”(哪个类对应哪张表,哪个属性对应
// 哪一列)。它们的作用相当于 TypeORM 的 @PrimaryGeneratedColumn、
// @Column 装饰器。
// =========================================================================

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace RdvMedecins.Entities;

public abstract class AbstractEntity
{
    // [Key]:主键。整数键按约定由数据库生成
    // (AUTO_INCREMENT 列):EF Core 在每次 INSERT 之后
    // 读回其值。
    [Key]
    [Column("id")]
    public int Id { get; set; }

    // [ConcurrencyCheck]:乐观锁。EF Core 生成的每个 UPDATE
    // 都带有条件 "WHERE id = ... AND version = <读取到的值>"。
    // 如果期间有人修改了该行,就不会有任何行
    // 被更新,EF Core 抛出 DbUpdateConcurrencyException。
    //
    // 与 TypeORM 的 @VersionColumn 的区别:EF Core 不会自行递增
    // 整数版本号。这由我们的 DbContext 完成,
    // 就在每次保存之前(见 Data/RdvMedecinsDbContext.cs)。
    [Column("version")]
    [ConcurrencyCheck]
    public int Version { get; set; }
}
  • 第 23 行:一个抽象类,没有 [[Table]] 特性:它不对应任何表,但其属性会添加到其子类对应的表中。应用程序中的所有实体都继承自它,因此都有标识符和版本;
  • 第 28–30 行:主键([[Key]]),列 [id]。按照 EF Core 的约定,整数键由数据库生成([AUTO_INCREMENT]):EF Core 在每次 [INSERT] 之后重新读取其值;
  • 第 40–42 行:用于乐观锁的行版本(参见示例 28)。[[ConcurrencyCheck]] 会在每条 [UPDATE] 中添加条件 [AND version = <value read>]。与 [@VersionColumn] (来自 [TypeORM])不同,EF Core 不会自行递增版本:由 [DbContext] 负责(见下文)。

11.8.2. Entities/Person.cs

// =========================================================================
// Entities/Person.cs
// -------------------------------------------------------------------------
// [Doctor] 和 [Client] 实体的父类(无表):称谓、
// 姓、名,以及关联的用户账户([user] 列)。
//
// 在抽象类中声明的关系会像列一样被
// 子类继承:因此 EF Core 会把 [User] 关系同时添加到 [doctors] 表
// 和 [clients] 表。
// =========================================================================

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace RdvMedecins.Entities;

public abstract class Person : AbstractEntity
{
    [Column("title")]
    [MaxLength(5)]
    public string Title { get; set; } = ""; // Melle、Mme、Mr

    [Column("last_name")]
    [MaxLength(20)]
    public string LastName { get; set; } = "";

    [Column("first_name")]
    [MaxLength(20)]
    public string FirstName { get; set; } = "";

    // -----------------------------------------------------------------------
    // 到用户账户的关系,用两个属性表示,这是 EF Core 的
    // 常规做法:
    //   - UserId:外键本身([user] 列)。无需加载完整的 User
    //     即可读取(TypeORM:@RelationId);
    //   - User:“导航属性”,即 User 对象本身。
    //     只有在查询中请求时才会填充(.Include(...),
    //     见 Repositories/),否则为 null。
    // [ForeignKey] 将两者关联起来。关系的“一对一”性质
    // ([user] 列 UNIQUE)在 RdvMedecinsDbContext 中指定。
    // -----------------------------------------------------------------------
    [Column("user")]
    public int UserId { get; set; }

    // "= null!":我们向编译器保证,只有在此属性已被加载(Include)
    // 或已被赋值时才会读取它
    [ForeignKey(nameof(UserId))]
    public User User { get; set; } = null!;
}
  • 第 17 行:[Doctor] 和 [Client] 的父类(它同样是抽象的),本身是 [AbstractEntity] 的子类。医生和客户具有相同的列:它们只定义一次;
  • 第 19–29 行:称谓(Mme、Mr、Melle)、姓和名。[[MaxLength]] 指定列宽。这些属性的类型为 [string] (而不是 [string?]):它们绝不能被设为 [null],因此编译器要求一个初始值,这里是空字符串 [""];
  • 第 42–43 行:指向用户账户的外键,列 [user]。无需加载账户本身即可读取账户标识符:这就是 [@RelationId] 在 [NestJS] 版本中所起的作用;
  • 第 47–48 行:导航属性:即 [User] 对象本身。[[ForeignKey(nameof(UserId))]] 指明哪个属性包含外键([nameof(UserId)] 等于字符串 ["UserId"],但编译器会验证该属性确实存在)。只有当查询要求时,导航属性才会被填充([Include];参见 DAO 层);否则它被设为 [null]。写法 [= null!] 会抑制编译器警告:它保证该属性只会在加载之后才被读取。“一对一”关系在 [DbContext] 中指定。在父类中声明的关系会像列一样被继承:表 [doctors] 和 [clients] 各自都有与 [users] 的关系。

11.8.3. Entities/Doctor.cs

// =========================================================================
// Entities/Doctor.cs
// -------------------------------------------------------------------------
// 诊所的一名医生([doctors] 表)。
//
// SQL 唯一性约束:unq_doctors_first_name_last_name(两名医生
// 不能有相同的姓和名),由 SQL 脚本创建,
// 在业务层中通过其名称识别。
// =========================================================================

using System.ComponentModel.DataAnnotations.Schema;

namespace RdvMedecins.Entities;

[Table("doctors")]
public class Doctor : Person
{
    // 反向(可选)关系:该医生的时间段。
    // 它以两个方向展示“1 名医生 -> 多个时间段”的关系;
    // 与任何导航属性一样,只在需要时才填充。
    public List<Slot> Slots { get; set; } = [];
}
  • 第 15 行:类 [Doctor] 对应表 [doctors]。它从 [Person] 继承其全部属性。注释中提到的唯一性约束 [unq_doctors_first_name_last_name] 由 SQL 脚本创建;业务层通过其名称识别它(参见示例 28);
  • 第 21 行:[Slot] 到其医生的关系的反向关系:该医生的预约时段。EF Core 会自动将这两个导航关联起来([Doctor.Slots] 和 [Slot.Doctor]),它们从各自一侧描述同一个“一个医生,多个时段”的关系。与任何导航一样,它只在请求时才会被填充;应用程序实际上并不 使用它:它通过 DAO 层读取预约时段。[[]] 是一个 集合表达式:这里是一个空列表。

11.8.4. Entities/Client.cs

// =========================================================================
// Entities/Client.cs
// -------------------------------------------------------------------------
// 注意:这里的 [Client] 指的是诊所的患者,而不是
// HTTP 客户端!这是原始业务领域的词汇,原样保留
// ([clients] 表)。
//
// SQL 唯一性约束:unq_clients_first_name_last_name(见 Doctor.cs)。
// =========================================================================

using System.ComponentModel.DataAnnotations.Schema;

namespace RdvMedecins.Entities;

[Table("clients")]
public class Client : Person
{
}

客户,即诊所的患者(而不是 HTTP 客户端):来自 [Person] 的 [clients] 表(第 15 行),没有额外的属性。

11.8.5. Entities/Slot.cs

// =========================================================================
// Entities/Slot.cs
// -------------------------------------------------------------------------
// 医生的一个时间段([slots] 表):8:00 - 8:20,等等。
// =========================================================================

using System.ComponentModel.DataAnnotations.Schema;

namespace RdvMedecins.Entities;

[Table("slots")]
public class Slot : AbstractEntity
{
    [Column("start_hour")] public int StartHour { get; set; } // 时间段的开始小时
    [Column("start_minute")] public int StartMinute { get; set; } // 时间段的开始分钟
    [Column("end_hour")] public int EndHour { get; set; } // 时间段的结束小时
    [Column("end_minute")] public int EndMinute { get; set; } // 时间段的结束分钟

    // 同一医生的多个时间段:外键 [doctor_id]
    // + 导航属性 [Doctor](与 Person.UserId / User 的技术相同)
    [Column("doctor_id")]
    public int DoctorId { get; set; }

    [ForeignKey(nameof(DoctorId))]
    public Doctor Doctor { get; set; } = null!;
}
  • 第 14–17 行:时段开始和结束的小时与分钟。特性和属性写在同一行:这是允许的,对于这四个相似的列来说更为紧凑;
  • 第 21–25 行:指向医生的“多对一”关系:一个医生对应多个时段。技术与 [Person] 中相同:外键 [DoctorId] (列 [doctor_id]) 和导航属性 [Doctor],通过 [[ForeignKey]] 关联。EF Core 不需要进一步说明:一侧是引用,另一侧是列表,这就是“一对多”关系。

11.8.6. Entities/Appointment.cs

// =========================================================================
// Entities/Appointment.cs
// -------------------------------------------------------------------------
// 一次预约([appointments] 表):一名客户端,在某个时间段,在某一天。
//
// SQL 唯一性约束:unq1_appointments (day, slot_id):每个时间段
// 每天只能被预订一次。由 SQL 脚本创建,在业务层中
// 通过其名称识别。
// =========================================================================

using System.ComponentModel.DataAnnotations.Schema;

namespace RdvMedecins.Entities;

[Table("appointments")]
public class Appointment : AbstractEntity
{
    // DateOnly:不带时间的日期,正好对应 [day] 列的 SQL 类型
    // DATE。(NestJS 项目使用字符串
    // "yyyy-MM-dd":JavaScript 没有“不带时间的日期”类型。)
    // 两个 DateOnly 值可以直接比较:day < today……
    [Column("day")]
    public DateOnly Day { get; set; }

    [Column("client_id")]
    public int ClientId { get; set; }

    [ForeignKey(nameof(ClientId))]
    public Client Client { get; set; } = null!;

    [Column("slot_id")]
    public int SlotId { get; set; }

    [ForeignKey(nameof(SlotId))]
    public Slot Slot { get; set; } = null!;
}
  • 第 15 行:预约表。其唯一性约束 [unq1_appointments (day, slot_id)] 确保一个时段每天只能被预订一次;
  • 第 22–23 行:预约的日期。类型 [DateOnly] (不带时间的日期)与 SQL 类型 [DATE] 完全对应:没有时间,因此没有时区问题。[NestJS] 版本处理的是 [yyyy-mm-dd] 类型的字符串,因为 [JavaScript] 中没有这样的类型。两个 [DateOnly] 值可以直接用 [<]、[>=] 等进行比较,无论是在 [C#] 中还是在 [LINQ] 查询中;
  • 第 25–35 行:客户和预约时段:两个“多对一”关系,每个都通过外键和导航属性定义。要创建预约,只需填充外键 [ClientId] 和 [SlotId]:业务层正是这样做的。

11.8.7. Entities/Role.cs

// =========================================================================
// Entities/Role.cs
// -------------------------------------------------------------------------
// 用户的三种角色(users.role 列):
//   - ADMIN:管理员,负责预约以及医生和客户端的管理;
//   - DOCTOR:医生,预订和取消预约;
//   - USER:客户端(患者),为自己预订,管理自己的账户。
//
// 在 C# 中使用枚举(enum)而不是字符串联合类型
// ('ADMIN' | 'DOCTOR' | 'USER'):编译器会拒绝任何其他值。
// EF Core 将其以文本('ADMIN'……)存入数据库,与
// SQL 脚本一致(见 RdvMedecinsDbContext 中的 HasConversion<string>())。
// =========================================================================

namespace RdvMedecins.Entities;

public enum Role
{
    ADMIN,
    DOCTOR,
    USER,
}
  • 第 17–21 行:三个角色,以 枚举 ([enum])的形式表示:[Role] 类型的变量只能取值 [Role.ADMIN]、[Role.DOCTOR] 或 [Role.USER],编译器会拒绝任何其他值。这等价于 [NestJS] 版本中的字符串联合类型 ['ADMIN' | 'DOCTOR' | 'USER']。默认情况下,EF Core 会将枚举存储为数字(0、1、2);[role] 列包含文本:转换是在 [DbContext] 中请求的。

11.8.8. Entities/User.cs

// =========================================================================
// Entities/User.cs
// -------------------------------------------------------------------------
// 允许登录应用程序的用户([users] 表)。
// 每位医生和每位客户端都有自己的用户账户([doctors] 和 [clients] 表的
// [user] 列,见 Person.cs)。
//
// SQL 唯一性约束:unq_users_login(一个登录名只属于一个
// 账户)。它由 database/dbrdvmedecins2.sql 脚本创建;
// 业务层通过其名称识别它(见 Business/BusinessService.cs)。
// =========================================================================

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace RdvMedecins.Entities;

[Table("users")]
public class User : AbstractEntity
{
    [Column("login")]
    [MaxLength(30)]
    public string Login { get; set; } = "";

    // 经过哈希的密码(bcrypt),绝不存明文
    [Column("password")]
    [MaxLength(100)]
    public string Password { get; set; } = "";

    // 登录后显示的名称:对医生或客户端而言为
    // "firstName LASTNAME"(例如 "Marie PELISSIER")
    [Column("name")]
    [MaxLength(40)]
    public string Name { get; set; } = "";

    // ADMIN、DOCTOR 或 USER,在数据库中以文本存储
    [Column("role")]
    public Role Role { get; set; }
}
  • 第 18 行:获准登录的用户账户:管理员、每位医生和每位客户。约束 [unq_users_login] 禁止两个账户使用相同的登录名;
  • 第 21–23 行:用户名;
  • 第 26–28 行:密码的 哈希 [bcrypt] ,绝不是密码本身(参见示例 25);
  • 第 32–34 行:登录后显示在导航栏中的名称(“Marie PELISSIER”);
  • 第 37–38 行:角色,类型为 [Role]。由于类 [User] 没有声明指向拥有它的医生或客户的导航,因此该关系只在 [Person] 一侧可知。

11.9. DbContext

应用程序中的 [DbContext] 以示例 28 中的 DbContext 为基础,包含五个表而不是一个,并对特性无法表达的模型细节作了一些补充说明。

11.9.1. Data/RdvMedecinsDbContext.cs

// =========================================================================
// Data/RdvMedecinsDbContext.cs
// -------------------------------------------------------------------------
// DbContext 是 Entity Framework Core 的核心部分。它同时
// 扮演以下角色:
//   - TypeORM 的 DataSource:到数据库的连接;
//   - TypeORM 的 Repository<T>:每张表一个 DbSet<T>,可
//     用 LINQ 查询(db.Doctors.Where(...)...);
//   - “工作单元”:它跟踪已加载的实体
//     (变更跟踪)。修改属性时,不会向数据库发送任何内容;
//     是 SaveChangesAsync() 一次性发送
//     必要的 INSERT / UPDATE / DELETE。
//
// 生命周期:每个 HTTP 请求一个 DbContext(“scoped”注册,
// 见 Program.cs)。因此同一请求的所有仓库共享
// 同一个 DbContext,从而共享同一个连接,以及业务层开启事务时
// 的同一个事务。
//
// 类 <-> 表的映射主要由实体的特性
// ([Table]、[Column]、[ForeignKey]……)描述;OnModelCreating 补充
// 特性无法表达的部分。
// =========================================================================

using Microsoft.EntityFrameworkCore;
using RdvMedecins.Entities;

namespace RdvMedecins.Data;

public class RdvMedecinsDbContext(DbContextOptions<RdvMedecinsDbContext> options) : DbContext(options)
{
    // 每个实体一张“表”。Set<T>() 返回 EF Core 为类型 T 创建的
    // DbSet。
    public DbSet<Doctor> Doctors => Set<Doctor>();
    public DbSet<Client> Clients => Set<Client>();
    public DbSet<Slot> Slots => Set<Slot>();
    public DbSet<Appointment> Appointments => Set<Appointment>();
    public DbSet<User> Users => Set<User>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // 一名医生(客户端)只有一个账户,而一个账户至多属于
        // 一个人(SQL 脚本中 [user] 列 UNIQUE):“一对一”
        // 关系,其外键由 doctors.user
        // (clients.user)承载。没有这一说明,EF Core 会假定“多名
        // 医生共用同一个账户”,这样也能工作,但
        // 对模型的描述会不准确。
        modelBuilder.Entity<Doctor>().HasOne(d => d.User).WithOne().HasForeignKey<Doctor>(d => d.UserId);
        modelBuilder.Entity<Client>().HasOne(c => c.User).WithOne().HasForeignKey<Client>(c => c.UserId);

        // 角色是 C# 枚举,在数据库中以文本存储
        // ('ADMIN'、'DOCTOR'、'USER'),而不是数字(0、1、2)
        modelBuilder.Entity<User>().Property(u => u.Role).HasConversion<string>();
    }

    // -----------------------------------------------------------------------
    // 乐观锁(见 AbstractEntity.Version):就在每次
    // 保存之前,我们递增每个被修改实体的版本。
    // EF Core 在 UPDATE 的 WHERE 子句中比较旧值
    // (从数据库读取的值),并写入新值:
    //     UPDATE doctors SET last_name = ..., version = 4 WHERE id = 1 AND version = 3
    //
    // ChangeTracker:DbContext 的“变更跟踪”。对每个已加载的实体,
    // 它知道该实体是已添加(Added)、已修改
    // (Modified)、已删除(Deleted)还是保持原样(Unchanged)。
    //
    // SaveChanges(Async) 的所有变体最终都会调用此方法。
    // -----------------------------------------------------------------------
    public override Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = default)
    {
        foreach (var entry in ChangeTracker.Entries<AbstractEntity>())
        {
            if (entry.State == EntityState.Modified)
            {
                entry.Entity.Version++;
            }
        }
        return base.SaveChangesAsync(acceptAllChangesOnSuccess, cancellationToken);
    }
}

下面对这段代码进行说明:

  • 第 29 行:与示例 28 中一样,[DbContext] 通过 [MySQL] 提供程序和连接字符串等选项,由 [AddDbContext] 在 [Program.cs] 中提供。它以 [Scoped] 生命周期注册:每个请求一个 [DbContext] ,由该请求的所有仓库共享,也就是说只有一个连接,必要时也只有一个事务。因此它同时承担了 [DataSource] 和 [Repository<T>] 在 [TypeORM] 中的角色;
  • 第 33–37 行:每个表一个 [DbSet]。[AbstractEntity] 和 [Person] 都没有对应的 DbSet:这些抽象类没有表。EF Core 不会将它们作为实体纳入模型;它只是把它们的属性添加到子类的属性中;
  • 第 39 行:[OnModelCreating] 在 EF Core 构建其 模型 (对表和关系的描述)时调用一次。它通过 流式 API(即一连串的方法调用)来补充实体特性;
  • 第 47–48 行:医生(客户同理)与其账户之间的关系是“一对一”:[HasOne(d => d.User)] (一个医生有一个账户)、[WithOne()](一个账户至多对应一个医生;空括号表示 [User] 没有反向导航)、[HasForeignKey<Doctor>(d => d.UserId)] (外键位于表 [doctors] 中)。如果没有 这几行,EF Core 会假定为“多对一”关系(多个医生对应同一个账户),这样同样能运行,但对模型的描述并不准确:在数据库中,[user] 列是唯一的;
  • 第 52 行:[HasConversion<string>()] 将角色以文本形式(['ADMIN'] 等)存储在数据库中,并在读取时将其转换回 [Role] ;
  • 第 68–77 行:每个被修改的实体的版本号在保存前递增,与示例 28 中一样。[ChangeTracker.Entries<AbstractEntity>()] 遍历所有其类派生自 [AbstractEntity] 的被跟踪实体:得益于共同的父类,这一个循环适用于全部五个表。[SaveChangesAsync] 的这个重载被重新定义为带两个参数,因为最终调用不带参数的 [SaveChangesAsync()] 的正是这个重载。EF Core 在 旧 版本的 [WHERE] 子句中与 [UPDATE] 比较并写入新版本:如果该行在此期间已被更改,则不会修改任何行,EF Core 会引发 [DbUpdateConcurrencyException]。

11.10. 领域:日程

[Domain] 文件夹包含两个不对应任何表的类:它们描述医生某一天的日程,由业务层计算([BusinessService.GetDoctorDayScheduleAsync]),并由日程控制器显示。

11.10.1. Domain/DoctorDaySlot.cs

// =========================================================================
// Domain/DoctorDaySlot.cs
// -------------------------------------------------------------------------
// 一个“业务”对象(无表),它将一个时间段与
// 该时间段在某一天可能被预订的预约关联起来。
//
// C# 的“record”是一个其属性由构造函数一次性
// 设定的类(不可变对象):正适合
// 一个计算得出、事后无人修改的对象。
// =========================================================================

using RdvMedecins.Entities;

namespace RdvMedecins.Domain;

// Appointment?:该时间段当天空闲时为 null
public record DoctorDaySlot(Slot Slot, Appointment? Appointment);
  • 第 17 行:一个时段,以及该日该时段所安排的预约,如果该时段可用则为 [null] (因此类型为 [Appointment?])。以这种方式编写的 [record] ,其参数写在括号中(位置记录),只用一行就声明了一个类、它的构造函数及其属性 [Slot] 和 [Appointment],这些属性在构造之后不能修改:这等价于 [constructor(public slot: Slot, ...)] 语法在 [NestJS] 版本中的用法。我们之前已经遇到过用于向业务层传递数据的记录(参见示例 28)。

11.10.2. Domain/DoctorDaySchedule.cs

// =========================================================================
// Domain/DoctorDaySchedule.cs
// -------------------------------------------------------------------------
// 医生某一天的完整日程:其时间段列表,
// 每个时间段要么空闲,要么已被某个预约占用。由
// BusinessService.GetDoctorDayScheduleAsync 计算,由
// ScheduleController 转换为 HTML 表格。
// =========================================================================

using RdvMedecins.Entities;

namespace RdvMedecins.Domain;

public record DoctorDaySchedule(Doctor Doctor, DateOnly Day, List<DoctorDaySlot> DoctorDaySlots);

日程(第 14 行):一个医生、一天,以及其可用或已预订时段的列表,按时间顺序排列。

11.11. DAO 层

每个表一个类,与示例 28 中相同:方法简短,没有业务逻辑,只负责查询或修改数据库。这里它们被称为“仓库”,与 [NestJS] 版本一致。与该版本有两点不同:

  • 查询用 [LINQ] 编写,由 EF Core 将其翻译为 SQL:通过导航属性从一个实体导航到另一个实体,连接由 EF Core 自行编写;
  • 这些方法没有用于事务的 [manager] 参数:一次请求中的所有仓库共享同一个 [DbContext],业务层在此 [DbContext] 上开启的事务会自动涵盖它们的所有查询。

所有方法都是异步的,并返回 [Task]:调用方使用 [await] 等待它。许多方法采用 [=> expression] 的形式编写:它们直接返回请求的 [Task] ,不使用 [async] 或 [await],因为之后没有其他事情要做。

11.11.1. Repositories/PersonRepository.cs

在 [NestJS] 版本中,医生和客户的仓库除了一行代码之外完全相同。在 [C#] 中,泛型类 只需编写一次。

// =========================================================================
// Repositories/PersonRepository.cs
// -------------------------------------------------------------------------
// 医生和客户端共用的 DAO 层。
//
// NestJS 项目的两个 DAO(DoctorRepository、ClientRepository)
// 除了一行之外完全相同。在 C# 中,一个泛型类只需写一次:
// PersonRepository<T>,其中 T 是 Doctor 或 Client。
// "where T : Person" 保证 T 具有 LastName、FirstName、User……
//
// 事务:这些方法不再需要 TypeORM 的可选 EntityManager 参数。
// 一个请求的所有仓库共享
// 同一个 DbContext(见 Data/RdvMedecinsDbContext.cs):当业务层
// 在此 DbContext 上开启事务时,它们的所有查询
// 都自动纳入其中。
// =========================================================================

using Microsoft.EntityFrameworkCore;
using RdvMedecins.Data;
using RdvMedecins.Entities;

namespace RdvMedecins.Repositories;

public abstract class PersonRepository<T>(RdvMedecinsDbContext db) where T : Person
{
    protected readonly RdvMedecinsDbContext db = db;

    // 类型 T 的人员“表”(db.Doctors 或 db.Clients)
    protected DbSet<T> Table => db.Set<T>();

    // 按姓再按名排序的列表,包含用户账户。
    // Include(p => p.User):通过连接同时带回账户
    // (SELECT ... FROM doctors INNER JOIN users ...)。没有它,p.User
    // 将为 null。
    // AsNoTracking():这些列表由缓存保存在内存中
    // (Web/ApplicationModel.cs),远超出 HTTP 请求的生命周期:让 DbContext
    // 跟踪它们既无用又耗费资源。
    public Task<List<T>> FindAllAsync() =>
        Table.AsNoTracking().Include(p => p.User).OrderBy(p => p.LastName).ThenBy(p => p.FirstName).ToListAsync();

    public Task<T?> FindByIdAsync(int id) =>
        Table.Include(p => p.User).FirstOrDefaultAsync(p => p.Id == id);

    // 用户账户为 [userId] 的人员,或 null
    public Task<T?> FindByUserIdAsync(int userId) =>
        Table.Include(p => p.User).FirstOrDefaultAsync(p => p.UserId == userId);

    // 具有这些姓和名的人员(如果存在)。比较
    // 由 MySQL 完成,因此采用数据库的排序规则
    // (utf8mb4_unicode_ci:不区分大小写和重音),这
    // 与 SQL 唯一性约束的规则完全相同。
    public Task<T?> FindByFirstNameLastNameAsync(string firstName, string lastName) =>
        Table.FirstOrDefaultAsync(p => p.FirstName == firstName && p.LastName == lastName);

    // 创建(Id = 0:尚未在数据库中)或更新(实体已被
    // DbContext 跟踪:SaveChanges 会自行检测哪些内容发生了变化)
    public async Task<T> SaveAsync(T person)
    {
        if (person.Id == 0)
        {
            Table.Add(person);
        }
        await db.SaveChangesAsync();
        return person;
    }

    // ExecuteDeleteAsync(EF Core 7+):直接发送到数据库的 DELETE,
    // 无需先加载实体: DELETE FROM doctors WHERE id = ?
    public Task DeleteByIdAsync(int id) => Table.Where(p => p.Id == id).ExecuteDeleteAsync();
}

// 两个具体的 DAO:一切都从基类继承
public class DoctorRepository(RdvMedecinsDbContext db) : PersonRepository<Doctor>(db);

public class ClientRepository(RdvMedecinsDbContext db) : PersonRepository<Client>(db)
{
    // -----------------------------------------------------------------------
    // 读取一名客户端,同时对其行加锁,直到当前事务
    // 结束(SELECT ... FOR UPDATE)。请求同一把锁的第二个事务
    // 会等待第一个事务完成。
    // 用于预订预约(见 BusinessService.AddAppointmentAsync):
    // 同一患者的两次同时预订因此会
    // 一个接一个处理,第二个能看到第一个创建的预约。
    //
    // LINQ 无法表达 "FOR UPDATE":我们自己编写 SQL 查询。
    // FromSqlInterpolated 会把 {id} 转换为 SQL 参数(不做
    // 字符串拼接,因此不可能发生 SQL 注入)。
    // -----------------------------------------------------------------------
    public async Task<Client?> LockAsync(int id)
    {
        var clients = await Table.FromSqlInterpolated($"SELECT * FROM clients WHERE id = {id} FOR UPDATE").ToListAsync();
        return clients.FirstOrDefault();
    }
}

下面对这段代码进行说明:

  • 第 24 行:[PersonRepository<T>] 是一个 泛型类;[T] 是一个 类型参数,在使用该类时被替换为实际类型([Doctor] 或 [Client]),就像 [T] 在 [List<T>] 中那样。约束 [where T : Person] 只接受 [Person] 或其子类作为 [T]:这样编译器就知道 [T] 包含 [Id], [LastName], [FirstName], [UserId], [User] 等,并在查询中接受 [p.LastName] 。该类是抽象的:只使用下面列出的它的两个子类;
  • 第 26 行:主构造函数的 [db] 参数仅在该类内部可见。它被复制到一个 [protected] 字段中 ,以便子类([ClientRepository])可以访问它;
  • 第 29 行:类型为 [T] 的人员表。[db.Set<T>()] 将 [DbSet] 映射到此类型:[db.Doctors] 对应 [T = Doctor],[db.Clients] 对应 [T = Client];
  • 第 38–39 行:所有人员,按姓再按名排序([OrderBy],然后用 [ThenBy] 处理姓相同时的排序)。[Include(p => p.User)] 还通过连接加载每个人的账户([INNER JOIN users]):没有它,[p.User] 就等同于 [null]。账户用于在列表中显示登录名。[AsNoTracking()] (参见示例 28):这些列表在查询结束很久之后仍由 [ApplicationModel] 保存在内存中;无需 [DbContext] 对其进行处理。诸如 [p => p.LastName] 之类的表达式不会在 [C#] 中执行:EF Core 会解析它们并将其翻译为 SQL([ORDER BY last_name, first_name]);
  • 第 41–42 行:某个人员及其账户,或 [null]。这里没有 [AsNoTracking()]:业务层会修改检索到的人员(及其账户),然后调用 [SaveAsync];跟踪这两个对象的 [DbContext] 知道哪些内容发生了变化;
  • 第 45–46 行:账户为 [userId] 的人员。已登录的患者(其令牌中包含账户标识符)就是这样检索到自己的客户记录的。过滤条件针对外键本身([WHERE clients.user = ...]);与 [users] 的连接仅用于加载账户([Include]);
  • 第 52–53 行:可能存在的同名者。运算符 [==] 被转换为 SQL 的 [=] :比较由 [MySQL] 按数据库的排序规则执行,不区分大写字母和重音符号,与唯一性约束完全一样(参见示例 28)。使用 [C#] 进行比较则会区分大写字母;
  • 第 57–64 行:创建或修改,与示例 28 中相同:新的人员([Id] 设为 0)被添加到 [DbSet];已在系统中的人员则无需任何操作。注意:[SaveChangesAsync] 会保存 所有挂起的 [DbContext] 更改,而不仅仅是来自 [person] 的更改:同时被修改的账户也包含在同一次调用中;
  • 第 69 行:通过 [ExecuteDeleteAsync] 删除(参见示例 28):一条 [DELETE] 直接发送到数据库,无需事先读取。它不经过更改跟踪,因此也不经过乐观锁;
  • 第 73 行:医生仓库:[PersonRepository<Doctor>],没有其他内容。它将收到的 [DbContext] 转发给其父类的构造函数;末尾的分号取代了空的类体;
  • 第 75 行:客户仓库,带有一个额外的方法;
  • 第 89–92 行:带 锁读取客户:[SELECT ... FOR UPDATE] 会在该行上加锁,直到当前事务结束;请求同一把锁的另一个事务会等待,直到第一个事务完成。预约方法([BusinessService.AddAppointmentAsync])利用这一点,把同一位患者的两个同时发生的预订依次处理:第二个预订会看到第一个预订创建的预约,从而遵守“只能有一个即将到来的预约”这一规则。[LINQ] 无法表达 [FOR UPDATE]:必须使用 [FromSqlInterpolated] 自己编写 SQL 查询。字符串 [$"..."] 是一个 内插字符串;[FromSqlInterpolated] 不会原样复制它:花括号中的每个值([{id}])都会变成一个 SQL 参数。因此没有字符串拼接,也不可能发生 SQL 注入。查询按原样执行([ToListAsync]),然后取结果列表中的第一个客户([FirstOrDefault],在内存中):如果在 [LINQ] 运算符之后再添加 [FromSqlInterpolated] ,EF Core 就会把我们的 SQL 包装在一个子查询中。

11.11.2. Repositories/SlotRepository.cs

// =========================================================================
// Repositories/SlotRepository.cs
// -------------------------------------------------------------------------
// [Slot] 实体的 DAO 层。
// =========================================================================

using Microsoft.EntityFrameworkCore;
using RdvMedecins.Data;
using RdvMedecins.Entities;

namespace RdvMedecins.Repositories;

public class SlotRepository(RdvMedecinsDbContext db)
{
    public Task<Slot?> FindByIdAsync(int id) =>
        db.Slots.Include(s => s.Doctor).FirstOrDefaultAsync(s => s.Id == id);

    // 某医生的时间段,按时间顺序排列
    public Task<List<Slot>> GetAllSlotsAsync(int doctorId) =>
        db.Slots
            .Where(s => s.DoctorId == doctorId)
            .OrderBy(s => s.StartHour)
            .ThenBy(s => s.StartMinute)
            .ToListAsync();

    // 删除某医生的所有时间段(删除医生时):
    //   DELETE FROM slots WHERE doctor_id = ?
    public Task DeleteByDoctorAsync(int doctorId) =>
        db.Slots.Where(s => s.DoctorId == doctorId).ExecuteDeleteAsync();
}
  • 第 15–16 行:一个预约时段及其医生([Include]);
  • 第 19–24 行:某个医生的时段,按时间顺序排列:[Where] 过滤,[OrderBy] 和 [ThenBy] 排序(先按小时,再按开始分钟)。查询是逐个方法构建的,就像 [TypeORM] 的 QueryBuilder 一样,并且只有在调用 [ToListAsync] 时才会执行:[SELECT ... FROM slots WHERE doctor_id = @p ORDER BY start_hour, start_minute]。值 [doctorId] 同样作为 SQL 参数传递;
  • 第 28–29 行:使用单个 [DELETE] 删除某个医生的预约时段。业务层在删除医生之前调用它;否则外键 [slots.doctor_id] 会阻止删除。

11.11.3. Repositories/AppointmentRepository.cs

// =========================================================================
// Repositories/AppointmentRepository.cs
// -------------------------------------------------------------------------
// [Appointment] 实体的 DAO 层。
//
// 查询用 LINQ 编写:EF Core 将其转换为 SQL。我们通过导航属性
// (a.Slot.DoctorId)从一个实体导航到另一个实体,
// EF Core 自行写出必要的连接。
// =========================================================================

using Microsoft.EntityFrameworkCore;
using RdvMedecins.Data;
using RdvMedecins.Entities;

namespace RdvMedecins.Repositories;

public class AppointmentRepository(RdvMedecinsDbContext db)
{
    public Task<Appointment?> FindByIdAsync(int id) =>
        db.Appointments.Include(a => a.Client).Include(a => a.Slot).FirstOrDefaultAsync(a => a.Id == id);

    public async Task<Appointment> SaveAsync(Appointment appointment)
    {
        if (appointment.Id == 0)
        {
            db.Appointments.Add(appointment);
        }
        await db.SaveChangesAsync();
        return appointment;
    }

    public Task DeleteByIdAsync(int id) => db.Appointments.Where(a => a.Id == id).ExecuteDeleteAsync();

    // 某医生某一天的预约,包含客户端和时间段。
    // a.Slot.DoctorId:[appointments] 表不直接引用
    // 医生;EF Core 通过与 [slots] 的连接来获取。
    public Task<List<Appointment>> GetDoctorDayAppointmentsAsync(int doctorId, DateOnly day) =>
        db.Appointments
            .Include(a => a.Client)
            .Include(a => a.Slot)
            .Where(a => a.Slot.DoctorId == doctorId && a.Day == day)
            .ToListAsync();

    // 某客户端从 [fromDay] 日起(含当日)的预约,按
    // 时间顺序排列,包含时间段及该时间段的医生
    // (先 Include 再 ThenInclude:appointment -> slot -> doctor)
    public Task<List<Appointment>> FindUpcomingByClientAsync(int clientId, DateOnly fromDay) =>
        db.Appointments
            .Include(a => a.Slot).ThenInclude(s => s.Doctor)
            .Where(a => a.ClientId == clientId && a.Day >= fromDay)
            .OrderBy(a => a.Day)
            .ThenBy(a => a.Slot.StartHour)
            .ThenBy(a => a.Slot.StartMinute)
            .ToListAsync();

    // 某客户端从 [fromDay] 日起(含当日)的预约数量
    public Task<int> CountUpcomingByClientAsync(int clientId, DateOnly fromDay) =>
        db.Appointments.CountAsync(a => a.ClientId == clientId && a.Day >= fromDay);

    // 删除某客户端的所有预约(过去和未来的):
    //   DELETE FROM appointments WHERE client_id = ?
    public Task DeleteByClientAsync(int clientId) =>
        db.Appointments.Where(a => a.ClientId == clientId).ExecuteDeleteAsync();

    // 某医生的预约数量(过去或未来的):
    //   SELECT COUNT(*) FROM appointments INNER JOIN slots s ON ... WHERE s.doctor_id = ?
    public Task<int> CountByDoctorAsync(int doctorId) =>
        db.Appointments.CountAsync(a => a.Slot.DoctorId == doctorId);
}

下面对这段代码进行说明:

  • 第 19–20 行:一个带有客户及其时段的预约:两条 [Include] 记录,因此有两个连接;
  • 第 22–29 行:与人员相同的模式。实际上,它只用于创建:业务层生成一个 [Appointment],其中只填充了外键;在 [SaveChangesAsync] 之后,[appointment.Id] 包含数据库分配的标识符;
  • 第 32 行:取消预约;
  • 第 37–42 行:某个医生在指定日期的预约,每个预约都带有其患者和时段(相当于 [leftJoinAndSelect] 在 [NestJS] 版本中的用法)。[appointments] 表并不直接引用医生:[a.Slot.DoctorId == doctorId] 过滤条件通过 [Slot] 导航,EF Core 会添加与 [slots] 的连接。区分导航的两种用法很重要:在 [Where] 中,它用于过滤;只有 [Include] 才会把对象加载到结果中;
  • 第 47–54 行:某个客户从 [fromDay] 这一天起的预约,连同其时段 以及该时段的医生:[Include(a => a.Slot)] 加载时段,然后 [ThenInclude(s => s.Doctor)] 加载该时段的医生(两个级联连接)。排序先按日期,再按时段的时间。这就是“我的空间”中显示的内容;
  • 第 57–58 行:这些预约的数量([SELECT COUNT(*)]),用于“只能有一个即将到来的预约”规则。[CountAsync] 可以直接接受条件,[FirstOrDefaultAsync] 也是如此;
  • 第 62–63 行:删除某个客户的所有预约,包括过去和将来的:业务层在删除客户之前调用它,否则外键 [appointments.client_id] 会阻止删除;
  • 第 67–68 行:某个医生的预约数量,用于阻止删除有预约的医生。同样,[a.Slot] 导航生成一个连接([INNER JOIN slots]),而不加载任何内容:这就是 [innerJoin] 在 [NestJS] 版本中的对应用法。

11.11.4. Repositories/UserRepository.cs

// =========================================================================
// Repositories/UserRepository.cs
// -------------------------------------------------------------------------
// [User] 实体的 DAO 层。创建(或删除)医生或
// 客户端时,也会创建(或删除)其账户,见 Business/BusinessService.cs。
// =========================================================================

using Microsoft.EntityFrameworkCore;
using RdvMedecins.Data;
using RdvMedecins.Entities;

namespace RdvMedecins.Repositories;

public class UserRepository(RdvMedecinsDbContext db)
{
    // 没有用户具有该登录名时为 null
    public Task<User?> FindByLoginAsync(string login) => db.Users.FirstOrDefaultAsync(u => u.Login == login);

    public async Task<User> SaveAsync(User user)
    {
        if (user.Id == 0)
        {
            db.Users.Add(user);
        }
        await db.SaveChangesAsync();
        return user;
    }

    public Task DeleteByIdAsync(int id) => db.Users.Where(u => u.Id == id).ExecuteDeleteAsync();
}
  • 第 17 行:与此登录名关联的账户,或 [null]。它用于登录([AuthService]),以及在分配登录名之前验证其是否可用;
  • 第 19–26 行:创建或修改账户。要创建医生或客户,必须先创建其账户:该人员的外键需要账户标识符;
  • 第 29 行:删除账户。顺序与创建过程相反:业务层先删除引用该账户的人员,然后再删除账户。

11.12. 业务层

业务层包含应用程序的业务规则:不得预约过去的时间、每位患者只能有一个即将到来的预约、用户名和人员唯一,以及医生或客户的删除。它依靠 DAO 层(文件夹 [Repositories])进行读写,对 HTML 和界面语言一无所知。更确切地说,这就是示例 28 中的 [PersonsBusiness] 层。

11.12.1. Business/Dates.cs

// =========================================================================
// Business/Dates.cs
// -------------------------------------------------------------------------
// 今天的日期。它被业务规则使用(不允许预订过去的
// 时间,每位患者只能有一个未来的预约):因此它位于
// 业务层。Web 层复用它。
// =========================================================================

namespace RdvMedecins.Business;

public static class Dates
{
    // 今天的日期,按服务器的时区
    public static DateOnly Today() => DateOnly.FromDateTime(DateTime.Now);
}
  • 第 11 行:[static] 类不会被实例化;它只是将方法组织在一起,通过类名调用([Dates.Today()]);
  • 第 14 行:今天的日期,使用服务器的时区。[DateTime.Now] 同时返回日期和时间;[DateOnly.FromDateTime] 只返回日期(类型 [DateOnly] 已在示例 12 中介绍;这是 [appointments.day] 列的格式)。两个 [DateOnly] 值可以直接用 [<] 或 [>=] 比较;而处理 [NestJS] 版本中 [yyyy-mm-dd] 字符串时,必须自己生成这种格式。当前日期用于业务规则,因此位于业务层;Web 层会复用它(例如在 [ScheduleController] 中,用来判断某一天是否仍可预订)。

11.12.2. Business/BusinessException.cs

// =========================================================================
// Business/BusinessException.cs
// -------------------------------------------------------------------------
// 业务层在违反业务规则时(登录名已被占用、医生仍有预约、
// 时间段已被预订……)抛出的异常。它不携带文本,
// 而是携带一个翻译键
// (例如 "ERRORS.LOGIN_TAKEN"):由 Web 层在显示页面时
// 将其翻译为法语或英语
// (参见 i18n/fr.json、i18n/en.json)。
//
// BusinessException 不是异常情况:它是一种正常的答复
// ("该登录名已被占用"),会显示给用户。任何其他
// 异常才是真正的故障,最终会进入 500 错误页面。
// =========================================================================

namespace RdvMedecins.Business;

public class BusinessException(string key, IReadOnlyDictionary<string, string>? messageParams = null) : Exception(key)
{
    // 消息的翻译键
    public string Key { get; } = key;

    // 消息的可能参数({minutes}……)
    public IReadOnlyDictionary<string, string> Params { get; } = messageParams ?? new Dictionary<string, string>();
}
  • 第 18 行:当业务规则拒绝某个事务时抛出的异常(参见示例 28)。该类使用 主构造函数 (参数 [key] 和 [messageParams] 列在类名之后);[: Exception(key)] 将键传递给父类 [Exception] 的构造函数,后者将其设置为属性 [Message] (在错误日志中很有用)。与示例 28 的区别:该异常携带的不是英文文本,而是一个 翻译键 ([ERRORS.LOGIN_TAKEN])。因此业务层不了解界面语言:由 Web 层使用字典 [i18n/fr.json] 和 [i18n/en.json] 翻译该键(参见第 5 章);
  • 第 21 行:翻译键,只读(只有 [get] 而没有 [set]);
  • 第 24 行:任何消息参数,它们将替换翻译文本中形如 [{minutes}] 的占位符。[IReadOnlyDictionary] 是只读字典。[??] 运算符在未提供参数时返回空字典:Web 层永远不需要检查 [null]。[BusinessService] 抛出的异常实际上只使用不带参数的键。

[BusinessException] 不是错误:它是一种正常的响应(“此登录名已被占用”),控制器会拦截它并显示给用户,显示在页面上或弹出消息中。任何其他异常才是真正的错误,会导致 500 错误页面。

11.12.3. Business/IBusiness.cs

// =========================================================================
// Business/IBusiness.cs
// -------------------------------------------------------------------------
// 业务层的契约:读取、日程、预约、医生和客户的
// 管理。
//
// .NET 约定:异步方法返回 Task<T>(相当于
// Promise<T>),其名称以 "Async" 结尾。
// =========================================================================

using RdvMedecins.Domain;
using RdvMedecins.Entities;

namespace RdvMedecins.Business;

// 在"医生"或"客户"表单中输入的数据
public record PersonData
{
    public required string Title { get; init; } // Mr, Mme, Melle
    public required string LastName { get; init; }
    public required string FirstName { get; init; }

    // 创建:可选,默认为小写的姓
    // 更新:可选,若缺省则登录名保持不变
    public string? Login { get; init; }

    // 创建:可选,默认为登录名
    // 更新:可选,若缺省则密码保持不变
    public string? Password { get; init; }

    // 更新:显示表单时该记录的版本
    // (乐观锁,参见 AbstractEntity.Version)
    public int? Version { get; init; }
}

public interface IBusiness
{
    // 读取
    Task<List<Client>> GetAllClientsAsync();
    Task<List<Doctor>> GetAllDoctorsAsync();
    Task<List<Slot>> GetAllSlotsAsync(int doctorId);
    Task<List<Appointment>> GetDoctorDayAppointmentsAsync(int doctorId, DateOnly day);
    Task<Client?> GetClientByIdAsync(int id);
    Task<Doctor?> GetDoctorByIdAsync(int id);
    Task<Appointment?> GetAppointmentByIdAsync(int id);
    Task<Slot?> GetSlotByIdAsync(int id);
    Task<DoctorDaySchedule?> GetDoctorDayScheduleAsync(int doctorId, DateOnly day);

    /// <summary>用户账户为 [userId] 的客户(患者),或 null</summary>
    Task<Client?> GetClientByUserIdAsync(int userId);

    /// <summary>客户今天或将来的预约,包含时间段和医生</summary>
    Task<List<Appointment>> GetClientUpcomingAppointmentsAsync(int clientId);

    // 预约(ADMIN、DOCTOR、USER)
    /// <summary>
    /// 在以下情况抛出 BusinessException:
    /// - 日期已过去("ERRORS.PAST_DATE");
    /// - 患者已有一个未来的预约("ERRORS.PATIENT_HAS_UPCOMING_APPOINTMENT");
    /// - 该时间段当天已被预订("ERRORS.SLOT_ALREADY_BOOKED")。
    /// </summary>
    Task<Appointment> AddAppointmentAsync(DateOnly day, Slot slot, Client client);

    Task DeleteAppointmentAsync(Appointment appointment);

    // 医生(ADMIN)
    /// <summary>创建医生及其用户账户(DOCTOR 角色)</summary>
    Task<Doctor> AddDoctorAsync(PersonData data);

    /// <summary>更新医生及其用户账户</summary>
    Task<Doctor> EditDoctorAsync(int id, PersonData data);

    /// <summary>删除医生、其时间段及其账户,若有预约则拒绝</summary>
    Task DeleteDoctorAsync(int id);

    // 客户
    // (ADMIN;AddClientAsync 也用于患者注册,
    // EditClientAsync 和 DeleteClientAsync 由患者用于自己的账户)
    /// <summary>创建客户及其用户账户(USER 角色)</summary>
    Task<Client> AddClientAsync(PersonData data);

    Task<Client> EditClientAsync(int id, PersonData data);

    /// <summary>
    /// 删除客户、其账户及其所有预约(过去和将来的)。
    /// 由 ADMIN("患者"页面)和患者本人("管理我的账户")使用。
    /// </summary>
    Task DeleteClientAsync(int id);
}
  • 第 17–33 行:要创建或修改的医生或客户的数据,由 Web 层传递(参见示例 28)。[required] 要求提供称谓、姓和名;[init] 防止它们之后被修改(参见示例 18)。用户名和密码是可选的([string?]):创建时,它们默认为小写的姓名;修改时,只有输入了才会更改。[Version] 是显示编辑表单时所读取记录的版本:它用于乐观锁(见下文);
  • 第 36 行:业务层的 契约:其他层可以向它请求什么,而不指明如何完成(接口已在示例 06 中讨论)。按照 [.NET] 的惯例,异步方法返回 [Task<T>](相当于 [Promise<T>] 在 [JavaScript] 中的对应物),其名称以 [Async] 结尾;
  • 第 39–53 行:读取操作。类型后面跟着 [?] ([Task<Client?>])表示该方法可以返回 [null]:没有人拥有这个标识符。[/// <summary>] 注释是文档注释:当鼠标悬停在方法上时,[Visual Studio Code] 会显示它们;
  • 第 57–64 行:预约。[AddAppointmentAsync] 的注释列出了可能的错误代码:这是测试人员必须了解的契约的一部分;
  • 第 68–74 行:医生管理(仅限 ADMIN)。每位医生与其用户账户一起被创建、修改和删除;
  • 第 80–88 行:客户管理,逻辑相同。[AddClientAsync] 也用于注册患者,而 [EditClientAsync] 和 [DeleteClientAsync] 则用于管理自己账户的患者。

实现通过 [Program.cs] 中的这一行 [builder.Services.AddScoped<IBusiness, BusinessService>()] 注册:“当构造函数请求 [IBusiness] 时,为其提供一个 [BusinessService]”,每个请求一个([Scoped]),就像 [DbContext] 以及它所使用的 DAO 条目一样(参见示例 28 和第 6 章)。在 [NestJS] 中,[TypeScript] 接口在编译时消失:需要一个令牌([BUSINESS_TOKEN])和 [@Inject(BUSINESS_TOKEN)] 。在 [C#] 中,接口在运行时是存在的:接口本身就充当令牌。唯一接收 [IBusiness] 的服务是 [ApplicationModel] (文件夹 [Web]),它同时也实现了 [IBusiness]:因此控制器看到的是同一份契约,并额外增加了医生和客户列表的缓存。

11.12.4. Business/BusinessService.cs

这是应用程序中内容最全面的文件。我们将分五个连续的片段来展示它。

11.12.4.1. 描述符

// =========================================================================
// Business/BusinessService.cs
// -------------------------------------------------------------------------
// 业务层的实现。
//
// 医生和客户的管理遵循三条业务规则:
//
//   1. 一个人(医生或客户)及其用户账户总是
//      同时处理:它们在同一个事务中一起创建、更新和删除
//      要么全部成功,要么什么都不写入;
//   2. 登录名在整个应用中唯一,且两个医生(或
//      两个客户)不能有相同的名和姓;
//   3. 删除:
//      - 有预约的医生不能被删除(其
//        患者会在不知情的情况下失去预约):必须
//        先取消这些预约。其时间段随医生一起消失;
//      - 相反,客户会连同其所有预约(过去和
//        将来的)一起消失,无论删除来自 ADMIN 还是
//        患者本人。
//
// 此外还有两条预约规则,无论预订者的角色是什么
// (ADMIN、DOCTOR 或患者本人):
//   4. 不能预约过去的时间;
//   5. 一个患者同一时间只能有一个未来的预约。
//
// 医生和客户遵循完全相同的规则:公共代码
// 只写一次(泛型私有方法 XxxPersonAsync<T>),
// 并由一个小的"描述符"参数化,用来说明处理的是
// 哪种类型的人。
// =========================================================================

using System.Text.RegularExpressions;
using Microsoft.EntityFrameworkCore;
using MySqlConnector;
using RdvMedecins.Data;
using RdvMedecins.Domain;
using RdvMedecins.Entities;
using RdvMedecins.Repositories;

namespace RdvMedecins.Business;

public class BusinessService : IBusiness
{
    // bcrypt 加盐轮数,与 SQL 脚本中的相同($2b$10$...)
    private const int BcryptRounds = 10;

    // 业务规则中区分医生和客户的所有内容。
    // "where T : Person, new()":T 是 Person,并且可以写 new T()。
    private record PersonDescriptor<T>(
        PersonRepository<T> Dao,
        Role Role, // DOCTOR 或 USER
        string NotFoundKey, // 该人不存在时的消息
        string AlreadyExistsKey, // 相同的名和姓已存在时的消息
        // 可选:若存在,只要该人还有预约就拒绝删除
        // (CountAppointments > 0),消息为 HasAppointmentsKey
        Func<int, Task<int>>? CountAppointments = null,
        string? HasAppointmentsKey = null,
        // 可选:必须在删除该人之前删除的内容
        // (通过外键引用它的行)
        Func<int, Task>? BeforeDelete = null) where T : Person, new();

    private readonly RdvMedecinsDbContext db;
    private readonly DoctorRepository doctorRepository;
    private readonly ClientRepository clientRepository;
    private readonly SlotRepository slotRepository;
    private readonly AppointmentRepository appointmentRepository;
    private readonly UserRepository userRepository;
    private readonly PersonDescriptor<Doctor> doctorDescriptor;
    private readonly PersonDescriptor<Client> clientDescriptor;

    // 所有依赖项都由 ASP.NET Core 的依赖注入提供
    // (参见 Program.cs)。此处使用 DbContext 仅为了开启
    // 事务,查询本身仍在 DAO 层中。
    public BusinessService(
        RdvMedecinsDbContext db,
        DoctorRepository doctorRepository,
        ClientRepository clientRepository,
        SlotRepository slotRepository,
        AppointmentRepository appointmentRepository,
        UserRepository userRepository)
    {
        this.db = db;
        this.doctorRepository = doctorRepository;
        this.clientRepository = clientRepository;
        this.slotRepository = slotRepository;
        this.appointmentRepository = appointmentRepository;
        this.userRepository = userRepository;

        doctorDescriptor = new PersonDescriptor<Doctor>(
            doctorRepository,
            Role.DOCTOR,
            "ERRORS.DOCTOR_NOT_FOUND",
            "ERRORS.DOCTOR_ALREADY_EXISTS",
            CountAppointments: appointmentRepository.CountByDoctorAsync,
            HasAppointmentsKey: "ERRORS.DOCTOR_HAS_APPOINTMENTS",
            // 没有预约的医生仍可能有时间段:
            // 没有医生时这些时间段就没有意义,因此随医生一起删除(否则
            // 外键 slots.doctor_id 会禁止删除)
            BeforeDelete: slotRepository.DeleteByDoctorAsync);

        clientDescriptor = new PersonDescriptor<Client>(
            clientRepository,
            Role.USER,
            "ERRORS.PATIENT_NOT_FOUND",
            "ERRORS.PATIENT_ALREADY_EXISTS",
            // 没有 CountAppointments:客户的删除从不被拒绝;
            // 其预约(过去和将来的)随其一起删除(否则
            // 外键 appointments.client_id 会禁止删除)
            BeforeDelete: appointmentRepository.DeleteByClientAsync);
    }
  • 第 6–29 行:头部注释概述了该类所应用的五条业务规则;
  • 第 34 行:[MySQL] 驱动程序(参见第 9 章):该类使用其 [MySqlException] 异常来检测对唯一性约束的违反;
  • 第 42 行:该类实现了接口;它必须提供接口的所有方法;
  • 第 45 行:[bcrypt] 的成本因子(参见示例 25),与 SQL 脚本中密码的成本因子相同(前缀 [$2b$10$]);
  • 第 49–60 行:在业务规则方面区分医生与客户的一切内容:它们的 DAO、账户角色([DOCTOR] 或 [USER])、错误消息,以及删除时发生的事情。由于医生和客户遵循相同的规则,这些规则的代码只在 泛型方法(由类型 [T] 参数化)中编写一次,这些方法接受一个描述符。约束 [where T : Person, new()] 要求 [T] 继承自 [Person](因此可以读取 [LastName]、[FirstName]、[User] 等),并且具有无参数构造函数(因此可以编写 [new T()])。[Func<int, Task<int>>] 是接受一个 [int] 并返回 [Task<int>] 的函数的类型;[Func<int, Task>] 是不返回任何内容的异步函数的类型。这些参数有默认值([= null]):它们是可选的;
  • 第 62–69 行:类的字段:[DbContext]、五个 DAO 和两个描述符。[readonly] 防止它们在构造函数之后被修改;
  • 第 74–87 行:所有依赖项都由依赖注入提供。这里的 [DbContext] 仅用于开启事务:请求仍保留在 DAO 层。与示例 28 中一样,在一次请求期间,DAO 和业务层接收的是 同一个 [DbContext] ,因此使用同一个连接和同一个事务;
  • 第 89–99 行:医生描述符。命名参数 ([CountAppointments:], [HasAppointmentsKey:] 等)通过名称引用参数,这样可以跳过可选参数(因此下面的客户描述符省略了 [CountAppointments] 和 [HasAppointmentsKey])。[appointmentRepository.CountByDoctorAsync] 在这里并没有被调用:传递的是方法本身,它将在稍后被调用(因此方法可以用作类型为 [Func] 的值)。只要医生还有预约,就拒绝删除;不过,他们的时段会在删除医生之前被删除;
  • 第 101–109 行:客户描述符。没有 [CountAppointments]:删除客户永远不会被拒绝,其预约(过去和将来的)会在客户本身之前被删除;否则外键 [appointments.client_id] 会阻止删除。

11.12.4.2. 读取操作和日程

    // =======================================================================
    // 读取
    // =======================================================================

    public Task<List<Client>> GetAllClientsAsync() => clientRepository.FindAllAsync();

    public Task<List<Doctor>> GetAllDoctorsAsync() => doctorRepository.FindAllAsync();

    public Task<List<Slot>> GetAllSlotsAsync(int doctorId) => slotRepository.GetAllSlotsAsync(doctorId);

    public Task<List<Appointment>> GetDoctorDayAppointmentsAsync(int doctorId, DateOnly day) =>
        appointmentRepository.GetDoctorDayAppointmentsAsync(doctorId, day);

    public Task<Client?> GetClientByIdAsync(int id) => clientRepository.FindByIdAsync(id);

    public Task<Doctor?> GetDoctorByIdAsync(int id) => doctorRepository.FindByIdAsync(id);

    public Task<Appointment?> GetAppointmentByIdAsync(int id) => appointmentRepository.FindByIdAsync(id);

    public Task<Slot?> GetSlotByIdAsync(int id) => slotRepository.FindByIdAsync(id);

    public Task<Client?> GetClientByUserIdAsync(int userId) => clientRepository.FindByUserIdAsync(userId);

    public Task<List<Appointment>> GetClientUpcomingAppointmentsAsync(int clientId) =>
        appointmentRepository.FindUpcomingByClientAsync(clientId, Dates.Today());

    // 与 JSON 服务器(以及原始 Spring 项目)相同的算法
    public async Task<DoctorDaySchedule?> GetDoctorDayScheduleAsync(int doctorId, DateOnly day)
    {
        var doctor = await GetDoctorByIdAsync(doctorId);
        if (doctor is null)
        {
            return null;
        }
        var timeSlots = await GetAllSlotsAsync(doctorId);
        var bookings = await GetDoctorDayAppointmentsAsync(doctorId, day);
        // 时间段编号 -> 该时间段上预订的预约
        var bookingsBySlot = bookings.ToDictionary(booking => booking.SlotId);
        var doctorDaySlots = timeSlots
            .Select(slot => new DoctorDaySlot(slot, bookingsBySlot.GetValueOrDefault(slot.Id)))
            .ToList();
        return new DoctorDaySchedule(doctor, day, doctorDaySlots);
    }
  • 第 5–22 行:读取操作只是委托给 DAO 层。[=> expression] 语法(即 表达式主体)取代了 [{ return expression; }] 代码块。这些方法不是 [async]:它们直接返回来自 DAO 的 [Task] ,而不等待它;
  • 第 24–25 行:患者即将到来的预约:业务层向 DAO 提供当前日期;
  • 第 28–42 行:计算医生某一天的日程,使用与 [NestJS] 版本相同的算法。未知的医生返回 [null];否则,读取该医生的时段和当天的预约;
  • 第 38 行:[ToDictionary] 将预约存储在以时段标识符为键的字典中(相当于 [Map] 在 [NestJS] 版本中的用法)。有了字典,就无需为每个时段扫描预约列表;
  • 第 39–41 行:每个时段与其预约相关联,或与 [null] 相关联([GetValueOrDefault] 在键不存在时返回默认值 [null])。[Select] 转换列表中的每个元素(参见 [LINQ],第 9 章)。结果是 [DoctorDaySchedule] 对象,位于 [Domain] 文件夹中,日历视图将显示它。

11.12.4.3. 预约

    // =======================================================================
    // 预约
    // =======================================================================

    // -----------------------------------------------------------------------
    // 在事务中预订预约:
    //   1. 不能预约过去的时间;
    //   2. 锁定患者的行(SELECT ... FOR UPDATE):如果
    //      同一患者同时预订两个时间段(两个标签页、
    //      双击……),第二个事务等待第一个
    //      结束,然后会看到刚刚创建的预约;
    //   3. 每个患者只能有一个未来的预约;
    //   4. 最后是插入。如果该时间段刚被另一个
    //      患者占用,则由 SQL 约束 unq1_appointments(day, slot_id)
    //      拒绝插入,并由 TransactionAsync 翻译为 BusinessException。
    // -----------------------------------------------------------------------
    public Task<Appointment> AddAppointmentAsync(DateOnly day, Slot slot, Client client) =>
        TransactionAsync(async () =>
        {
            var today = Dates.Today();
            if (day < today)
            {
                throw new BusinessException("ERRORS.PAST_DATE");
            }
            if (await clientRepository.LockAsync(client.Id) is null)
            {
                throw new BusinessException("ERRORS.PATIENT_NOT_FOUND");
            }
            if (await appointmentRepository.CountUpcomingByClientAsync(client.Id, today) > 0)
            {
                throw new BusinessException("ERRORS.PATIENT_HAS_UPCOMING_APPOINTMENT");
            }
            // 我们填写外键:无需附加
            // Slot 和 Client 对象本身即可写入 [appointments] 行
            var appointment = new Appointment { Day = day, SlotId = slot.Id, ClientId = client.Id };
            return await appointmentRepository.SaveAsync(appointment);
        });

    public Task DeleteAppointmentAsync(Appointment appointment) => appointmentRepository.DeleteByIdAsync(appointment.Id);
  • 第 17–18 行:整个预订过程在一个事务中进行:该方法将一个异步 匿名函数([async () => { ... }])传递给 [TransactionAsync] (见下文),由它执行该任务;
  • 第 20–23 行:不得预约过去的时间。无论进行预订的人是什么角色(ADMIN、DOCTOR 或患者),这里都会验证该规则,即使 Web 层已经隐藏了过去日期的“预订”按钮:请求可以被手工构造;
  • 第 25–27 行:患者的记录被锁定:[LockAsync] 执行 [SELECT * FROM clients WHERE id = ... FOR UPDATE] (参见 [Repositories/PersonRepository.cs])。这是一种 悲观锁:它在处理开始之前获取,假定可能发生冲突,并一直保持到事务结束。如果没有它,同一患者同时发出的两个预订(两个标签页、双击)可能都会通过下面的测试,而此时两者都还没有把各自的预约写入数据库。有了这把锁,第二个事务会等待第一个事务完成,然后看到它创建的预约。找不到的患者(在此期间被删除)会被拒绝;
  • 第 29–31 行:每位患者只能有一个即将到来的预约;
  • 第 35–36 行:插入。只指定外键 [SlotId] 和 [ClientId] :无需关联 [Slot] 和 [Client] 对象即可写入 [appointments] 行。如果 另一位患者刚刚预订了同一时段,锁并不能阻止它(锁作用于该患者的行):拒绝该插入的是数据库的 [unq1_appointments (day, slot_id)] 唯一性约束,并且 [TransactionAsync] 会将该错误转换为带有键 [BusinessException] 的 [ERRORS.SLOT_ALREADY_BOOKED];
  • 第 39 行:取消预约:一条简单的 [DELETE],没有特定规则。

11.12.4.4. 管理医生和客户

    // =======================================================================
    // 医生和客户:公共方法委托给公共
    // 私有方法,并传入合适的描述符
    // =======================================================================

    public Task<Doctor> AddDoctorAsync(PersonData data) => AddPersonAsync(doctorDescriptor, data);

    public Task<Doctor> EditDoctorAsync(int id, PersonData data) =>
        EditPersonAsync(doctorDescriptor, id, data);

    public Task DeleteDoctorAsync(int id) => DeletePersonAsync(doctorDescriptor, id);

    public Task<Client> AddClientAsync(PersonData data) => AddPersonAsync(clientDescriptor, data);

    public Task<Client> EditClientAsync(int id, PersonData data) =>
        EditPersonAsync(clientDescriptor, id, data);

    // 客户、其账户及其所有预约(ADMIN,或患者
    // 本人通过"管理我的账户":同一方法,同一规则)
    public Task DeleteClientAsync(int id) => DeletePersonAsync(clientDescriptor, id);

    // -----------------------------------------------------------------------
    // 创建:先创建用户账户(该人引用它),
    // 再创建该人,全部在同一个事务中。
    // -----------------------------------------------------------------------
    private Task<T> AddPersonAsync<T>(PersonDescriptor<T> d, PersonData data) where T : Person, new()
    {
        var lastName = data.LastName.Trim().ToUpperInvariant();
        var firstName = data.FirstName.Trim();
        // 数据库 dbrdvmedecins2 的规则:登录名 = 小写的姓,
        // 密码 = 登录名,除非 ADMIN 输入了其他值
        var login = (string.IsNullOrEmpty(data.Login) ? lastName : data.Login).ToLowerInvariant();
        var password = string.IsNullOrEmpty(data.Password) ? login : data.Password;

        return TransactionAsync(async () =>
        {
            await CheckPersonUniqueAsync(d, firstName, lastName, null);
            await CheckLoginFreeAsync(login);

            var user = new User
            {
                Login = login,
                Password = BCrypt.Net.BCrypt.HashPassword(password, BcryptRounds),
                Name = $"{firstName} {lastName}",
                Role = d.Role,
            };
            await userRepository.SaveAsync(user);

            var person = new T { Title = data.Title, LastName = lastName, FirstName = firstName, User = user };
            return await d.Dao.SaveAsync(person);
        });
    }

    // -----------------------------------------------------------------------
    // 更新:该人及其账户(显示名 "firstName LASTNAME"
    // 必须随之更新;登录名和密码仅在
    // 输入了新值时才更改)。
    // -----------------------------------------------------------------------
    private Task<T> EditPersonAsync<T>(PersonDescriptor<T> d, int id, PersonData data)
        where T : Person, new() =>
        TransactionAsync(async () =>
        {
            var person = await d.Dao.FindByIdAsync(id) ?? throw new BusinessException(d.NotFoundKey);

            // 乐观锁:如果数据库中的版本不再是表单中的版本,
            // 说明其间有人修改了该记录,我们拒绝
            // 而不是悄悄覆盖其更改。
            // (如果并发更新发生在此次读取之后,则由
            // UPDATE 的 "WHERE version = ..." 子句检测到。)
            if (data.Version is not null && data.Version != person.Version)
            {
                throw new BusinessException("ERRORS.CONCURRENT_UPDATE");
            }

            // 我们只修改对象:跟踪它们的 DbContext 会在下一次 SaveChangesAsync 时
            // 发送必要的 UPDATE
            person.Title = data.Title;
            person.LastName = data.LastName.Trim().ToUpperInvariant();
            person.FirstName = data.FirstName.Trim();
            await CheckPersonUniqueAsync(d, person.FirstName, person.LastName, id);

            var user = person.User;
            user.Name = $"{person.FirstName} {person.LastName}";
            if (!string.IsNullOrEmpty(data.Login) && data.Login.ToLowerInvariant() != user.Login)
            {
                var login = data.Login.ToLowerInvariant();
                await CheckLoginFreeAsync(login);
                user.Login = login;
            }
            if (!string.IsNullOrEmpty(data.Password))
            {
                user.Password = BCrypt.Net.BCrypt.HashPassword(data.Password, BcryptRounds);
            }
            await userRepository.SaveAsync(user);
            return await d.Dao.SaveAsync(person);
        });

    // -----------------------------------------------------------------------
    // 在一个事务中删除,按外键要求的顺序:
    // 1. 若仍有预约则可能拒绝(医生);
    //   2. 引用该人的内容(医生的时间段、
    //   客户的预约);
    //      3. 该人本身
    //   (它引用其账户);
    //   4. 其账户。
    // -----------------------------------------------------------------------
    private Task DeletePersonAsync<T>(PersonDescriptor<T> d, int id) where T : Person, new() =>
        TransactionAsync(async () =>
        {
            var person = await d.Dao.FindByIdAsync(id) ?? throw new BusinessException(d.NotFoundKey);
            if (d.CountAppointments is not null && await d.CountAppointments(id) > 0)
            {
                throw new BusinessException(d.HasAppointmentsKey ?? "ERRORS.INVALID_FORM");
            }
            if (d.BeforeDelete is not null)
            {
                await d.BeforeDelete(id);
            }
            await d.Dao.DeleteByIdAsync(id);
            await userRepository.DeleteByIdAsync(person.UserId);
            return true; // TransactionAsync 期望有返回结果:这里不需要
        });

    // 拒绝同类型的另一个人已使用的名和姓
    // (currentId:正在更新的人,他当然有权
    // 保留自己的名和姓;创建时为 null)
    private static async Task CheckPersonUniqueAsync<T>(PersonDescriptor<T> d, string firstName, string lastName, int? currentId)
        where T : Person, new()
    {
        var namesake = await d.Dao.FindByFirstNameLastNameAsync(firstName, lastName);
        if (namesake is not null && namesake.Id != currentId)
        {
            throw new BusinessException(d.AlreadyExistsKey);
        }
    }

    private async Task CheckLoginFreeAsync(string login)
    {
        if (await userRepository.FindByLoginAsync(login) is not null)
        {
            throw new BusinessException("ERRORS.LOGIN_TAKEN");
        }
    }
  • 第 6–20 行:六个公共方法委托给三个私有泛型方法,并使用正确的描述符。编译器从描述符推断出 [T] :[doctorDescriptor] 对应 [Doctor],[clientDescriptor] 对应 [Client];
  • 第 26–50 行:创建人员及其账户;
  • 第 28–33 行:数据准备,在事务之外。[Trim] 去除字符串首尾的空格;姓名首字母大写。默认情况下,登录名与姓名相同,并且始终为小写;默认情况下,密码与登录名相同:这些是 SQL 脚本中的账户规则;
  • 第 37–38 行:在事务内部,两条唯一性规则:不允许重名,以及可自由选择的登录名。这些检查在写入数据库之前进行,以便给出清晰的消息(参见示例 28);
  • 第 40–47 行:先创建用户账户,因为人员引用它(外键)。密码绝不以明文存储:[BCrypt.Net.BCrypt.HashPassword] 计算其哈希(参见示例 25)。[$"{firstName} {lastName}"] 是一个内插字符串:账户的显示名称;
  • 第 49–50 行:然后,根据约束 [new()],使用 [new T] 来生成 [Doctor] 或 [Client] 人员。如果第二次写入操作失败,事务也会回滚第一次写入:账户绝不会在没有人员的情况下单独存在;
  • 第 59–95 行:在一个事务中修改人员及其账户;
  • 第 63 行:找不到人员会引发 [BusinessException],并带有描述符的键。[?? throw] 已在示例 28 中见过;
  • 第 70–72 行:乐观锁 (参见示例 28):表单在显示时带上了所读取记录的版本;如果数据库中的版本不同,说明有人在此期间修改了该记录,系统会拒绝更新,而不是悄无声息地覆盖他们的工作。与预订时使用的悲观锁不同,这里不会阻塞任何操作:我们假定冲突很少发生,只是检测冲突。如果并发修改发生在这次读取之后,则由 [WHERE version = ...] 条件(属于 [UPDATE] )来检测它(参见 [TranslateDatabaseError],见下文);
  • 第 77–80 行:只需修改读取到的对象:随后 [DbContext] 会在下一次 [SaveChangesAsync] 时发送必要的 [UPDATE]。姓名检查会传递该人员的标识符:他们当然有权保留自己的姓和名;
  • 第 82–88 行:账户随人员而变(导航属性 [User],由 DAO 加载):重新计算其显示名称。只有在输入了登录名且与当前登录名不同时才会更改登录名;这种情况下,它必须是可用的;
  • 第 90–92 行:只有在输入了密码时才会更改密码;随后对其进行哈希;
  • 第 94–95 行:保存账户和人员。我们的 [DbContext] 会递增每个被修改实体的版本号(参见 [Data/RdvMedecinsDbContext.cs]);
  • 第 107–121 行:在一个事务中,按外键所要求的顺序进行删除;
  • 第 111–113 行:可能的拒绝:有已安排预约的医生不能被删除(其患者会在不知情的情况下失去预约)。[d.CountAppointments(id)] 调用存储在描述符中的函数;
  • 第 115–117 行:删除引用该人员的内容:医生的时段、客户的预约;
  • 第 119–120 行:先删除人员,再删除该人员所引用的账户;
  • 第 121 行:[TransactionAsync] 需要一个返回结果的函数:这里返回了一个结果,但没有人会使用它;
  • 第 127–133 行:同名者会被拒绝,除非就是当前正在编辑的人员([currentId],新建时为 [null] )。该方法是 [static]:它不使用对象的任何字段;
  • 第 137–141 行:已被使用的登录名(无论被医生、客户还是管理员使用)会被拒绝。

11.12.4.5. 事务和唯一性约束

    // -----------------------------------------------------------------------
    // 在事务中运行 [work]:
    //   BeginTransactionAsync -> START TRANSACTION;
    //   CommitAsync -> COMMIT,如果一切顺利;
    //   如果抛出异常(包括 BusinessException),则不提交:
    //   "await using" 在离开代码块时关闭事务,而
    //   未经 COMMIT 就关闭的事务会被取消(ROLLBACK)。
    //
    // "登录名空闲"和"名加姓唯一"的检查在写入之前进行,
    // 以给出清晰的消息。但两个 ADMIN 可能
    // 同时保存相同的登录名(或相同的医生):在这种
    // 罕见情况下,由 SQL 唯一性约束拒绝第二次
    // 写入,然后我们把该 SQL 错误翻译为同样的 BusinessException。
    // -----------------------------------------------------------------------
    private async Task<R> TransactionAsync<R>(Func<Task<R>> work)
    {
        await using var transaction = await db.Database.BeginTransactionAsync();
        try
        {
            var result = await work();
            await transaction.CommitAsync();
            return result;
        }
        catch (Exception e)
        {
            // 失败时,DbContext 会"忘记"它跟踪的所有内容:
            // 否则处于 Added 状态的实体会在同一请求的
            // 下一次 SaveChangesAsync 时再次发送到数据库
            db.ChangeTracker.Clear();
            if (TranslateDatabaseError(e) is { } businessError)
            {
                throw businessError;
            }
            throw; // "throw;" 重新抛出原始异常,调用栈保持完整
        }
    }

    // -----------------------------------------------------------------------
    // 数据库错误 -> BusinessException
    //
    // - DbUpdateConcurrencyException:UPDATE "WHERE id = ... AND version = ..."
    //   没有修改任何行(乐观锁,参见 AbstractEntity);
    // - DbUpdateException,其原因(InnerException)为 MySQL 错误
    //   ER_DUP_ENTRY(编号 1062):某个 UNIQUE 约束拒绝了写入。其
    //   消息引用了约束的名称:
    //     Duplicate entry 'marie-pelissier' for key 'doctors.unq_doctors_first_name_last_name'
    //   (MySQL 8 在名称前加上表名,MariaDB 不加)。这就是
    //   SQL 脚本为所有约束命名的原因。
    // 任何其他错误都是真正的故障:返回 null(不翻译)。
    // -----------------------------------------------------------------------
    private static readonly Dictionary<string, string> ConstraintMessages = new()
    {
        ["unq_users_login"] = "ERRORS.LOGIN_TAKEN",
        ["unq_doctors_first_name_last_name"] = "ERRORS.DOCTOR_ALREADY_EXISTS",
        ["unq_clients_first_name_last_name"] = "ERRORS.PATIENT_ALREADY_EXISTS",
        ["unq1_appointments"] = "ERRORS.SLOT_ALREADY_BOOKED",
    };

    private static BusinessException? TranslateDatabaseError(Exception e)
    {
        // 注意顺序:DbUpdateConcurrencyException 继承自 DbUpdateException
        if (e is DbUpdateConcurrencyException)
        {
            return new BusinessException("ERRORS.CONCURRENT_UPDATE");
        }
        // "模式匹配":e 是否为 DbUpdateException,
        // 且其 InnerException 是代码为 DuplicateKeyEntry 的 MySqlException?
        if (e is DbUpdateException { InnerException: MySqlException { ErrorCode: MySqlErrorCode.DuplicateKeyEntry } sqlError })
        {
            // "... for key 'doctors.unq_doctors_first_name_last_name'" -> "unq_doctors_first_name_last_name"
            var match = Regex.Match(sqlError.Message, @"for key '(?:[^'.]*\.)?([^']+)'");
            if (match.Success && ConstraintMessages.TryGetValue(match.Groups[1].Value, out var key))
            {
                return new BusinessException(key);
            }
        }
        return null;
    }
}
  • 第 15 行:所有多步骤的写入都经过这个泛型方法:[R] 是操作结果的类型([Appointment]、[Doctor]、[Client]、[bool]),而 [Func<Task<R>>] 是 返回 [R] 的无参数异步函数的类型。这就是示例 28 中的 [TransactionAsync] 方法的扩展版本;
  • 第 17 行:[BeginTransactionAsync] 开启一个事务([START TRANSACTION])。[await using var] 声明一个变量,无论发生什么(正常结束或异常),它都会在退出包含它的代码块时自动关闭;[await] 版本允许异步关闭。未提交就关闭的事务会被回滚([ROLLBACK]);
  • 第 20–22 行:执行任务;如果成功,[CommitAsync] 提交事务([COMMIT])。如果抛出异常(包括 [BusinessException]),则[CommitAsync] 永远不会被执行:所有已写入的内容都会被回滚;
  • 第 24 行:示例 28 捕获了两种特定类型的异常;这里我们捕获所有异常,以便在重新抛出之前进行清理;
  • 第 29 行:清理。数据库已经回滚了所有内容,但 [DbContext] 仍在跟踪已不再对应任何内容的实体:例如,插入失败的医生仍处于 [Added] 状态。由于 [DbContext] 在整个请求期间一直存在,它会在该请求的下一次 [SaveChangesAsync] 时被再次发送到数据库。[ChangeTracker.Clear()] 会让 [DbContext] 忘记它所跟踪的所有实体;
  • 第 30–32 行:如果错误是已知的数据库错误,则改为引发相应的 [BusinessException]。[is { } businessError] 是一个模式过滤器:它检查该值不为 [null] ,并将其存储在变量 [businessError] 中;
  • 第 34 行:否则,原始异常将原样重新抛出。在 [throw;] 单独出现于 [catch] 中时,会保持其调用堆栈(指明错误发生位置的那个堆栈)完好无损,而 [throw e;] 则会将其重置。因此,由任务引发的 [BusinessException] 会原封不动地传回控制器;任何其他错误都是异常情况,会生成 500 错误页面;
  • 第 51–56 行:对于 SQL 脚本中每个具名的唯一性约束,给出其翻译键。这就是 SQL 脚本为其所有约束命名的原因。当左侧已指定类型时,允许使用不带类型名的 [new()];[["key"] = value] 填充字典;
  • 第 59–77 行:将数据库错误转换为 [BusinessException],如果无法识别该错误,则为 [null] ;
  • 第 62–64 行:[UPDATE ... WHERE id = ... AND version = ...] 没有修改任何行:EF Core 会引发 [DbUpdateConcurrencyException] (乐观锁;参见示例 28)。这个测试放在最前面,因为 [DbUpdateConcurrencyException] 继承自 [DbUpdateException]:如果放在后面,下面的测试就会先拦截它;
  • 第 68 行:违反唯一性约束。[MySQL] 错误(代码 [DuplicateKeyEntry],编号 1062)嵌套在 [DbUpdateException] 中,位于其属性 [InnerException] 里。模式过滤只用一个表达式就在两个层级上完成所有检查:[e] 是一个 [DbUpdateException],其 [InnerException] 是一个 [MySqlException],其 [ErrorCode] 等于 [DuplicateKeyEntry];这个 [MySqlException] 被包含在 [sqlError] 中。[NestJS] 版本还测试了 [ER_DUP_ENTRY] 代码,它属于 [QueryFailedError];
  • 第 71 行:错误消息列出了约束名称,例如 [Duplicate entry 'marie-pelissier' for key 'doctors.unq_doctors_first_name_last_name']。正则表达式将其提取出来:[(?:[^'.]*\.)?] 跳过可选的前缀 [doctors.] (由 [MySQL] 8 写入,而不是由 [MariaDB] 写入),而分组 [([^']+)] 捕获直到撇号为止的名称。字符串开头的 [@] 使其成为 逐字字符串,其中 [\] 不是转义字符;
  • 第 72–74 行:如果找到了该名称且它列在字典中,[TryGetValue] 会将翻译键存入 [key],错误随之变为 [BusinessException]。任何其他错误,包括对字典中没有的约束的违反,都不会被翻译:这才是真正的异常情况。

11.13. 身份验证

[Auth] 文件夹以更完整的形式包含了示例 25 至 27:Cookie 中的 JWT 令牌、角色、验证码(CAPTCHA)和尝试次数限制。它还包含用于创建客户账户的“通行码”。本节末尾讨论的 [AuthController] 控制器将这些组件整合到登录页面中。

11.13.1. Auth/ConnectedUser.cs

// =========================================================================
// Auth/ConnectedUser.cs
// -------------------------------------------------------------------------
// JWT 令牌包含什么,以及如何读回。
//
// 在 ASP.NET Core 中,请求的用户是一个 ClaimsPrincipal
// (控制器的 User 属性,其他地方为 HttpContext.User):一个
// "声明"列表,即类型 / 值对,恰好就是
// 验证后 JWT 令牌的字段。身份验证中间件在每个请求上
// 填充它(参见 Program.cs,UseAuthentication)。
//
// 我们令牌的声明(参见 AuthService.SetToken):
//   sub :用户账户的 id(JWT 约定:"subject")
//   login :登录名
//   name :显示名("Marie PELISSIER"),用于导航栏
//   role :ADMIN、DOCTOR 或 USER
// =========================================================================

using System.Security.Claims;
using RdvMedecins.Entities;

namespace RdvMedecins.Auth;

public static class JwtClaims
{
    public const string Sub = "sub";
    public const string Login = "login";
    public const string Name = "name";
    public const string Role = "role";
}

// 已连接的用户,以类型化形式表示
public record ConnectedUser(int UserId, string Login, string Name, Role Role);

// -------------------------------------------------------------------------
// "扩展方法":调用时就像它是
// ClaimsPrincipal 的一部分(User.CurrentUser()),而实际上它定义在此处。
// -------------------------------------------------------------------------
public static class ClaimsPrincipalExtensions
{
    // 已连接的用户,如果请求未经身份验证则为 null
    public static ConnectedUser? CurrentUser(this ClaimsPrincipal principal)
    {
        if (principal.Identity?.IsAuthenticated != true
            || !int.TryParse(principal.FindFirstValue(JwtClaims.Sub), out var userId)
            || !Enum.TryParse<Role>(principal.FindFirstValue(JwtClaims.Role), out var role))
        {
            return null;
        }
        return new ConnectedUser(
            userId,
            principal.FindFirstValue(JwtClaims.Login) ?? "",
            principal.FindFirstValue(JwtClaims.Name) ?? "",
            role);
    }
}
  • 第 24–29 行:令牌声明(claim)的名称,归为常量:[JwtClaims.Name] 中的拼写错误会被编译器标出,而字符串 ["name"] 中的错误则只会在运行时才被发现;
  • 第 33 行:已登录的用户,以带类型的形式表示:整数标识符、类型为 [Role] 的角色(来自 [Entities] 文件夹中的枚举 ADMIN、DOCTOR、USER),而不是构成声明的字符串对列表。这等价于 [req.user] 对象,它由 [Passport] 策略在 [NestJS] 项目中创建;
  • 第 39–42 行:***[ClaimsPrincipal] 上的扩展方法(参见示例 06),它是控制器和视图的 ***[User] 属性的类型(参见示例 25)。页面只需编写 [User.CurrentUser()];
  • 第 44–48 行:如果请求未经身份验证,或者声明不符合预期,该方法返回 [null] 。如果 [Identity?.IsAuthenticated] 缺少 [Identity],则 [Identity] 等于 null:[!= true] 比较将这种情况视为“未经身份验证”。[int.TryParse] 和 [Enum.TryParse<Role>] 尝试进行转换,如果转换失败则返回 [false] ,而不是抛出异常;结果存储在由 [out var] 声明的变量中;
  • 第 50–54 行:[FindFirstValue] 返回所请求类型的第一个声明的值,或 [null];然后运算符 [??] 将其替换为空字符串。

11.13.2. Auth/AuthService.cs

// =========================================================================
// Auth/AuthService.cs
// -------------------------------------------------------------------------
// 身份验证逻辑:
//   - ValidateUserAsync() :检查登录名 / 密码对;
//   - SetToken() :为已验证的用户构建 JWT 令牌
//                                并将其存入 Cookie;
//   - ClearToken() :删除该 Cookie(注销)。
//
// JWT 令牌通过什么传输?
// 使用 Angular 客户端时,由客户端的 JavaScript 代码保存
// 令牌,并自行将其添加到每个请求中("Authorization:
// Bearer ..." 头)。显示普通 HTML 页面的浏览器无法
// 这样做:要让它在每个请求中自动出示令牌,
// 就必须把令牌存放在 COOKIE 中。该 Cookie 的选项对
// 安全很重要:
//   - HttpOnly:页面的 JavaScript 无法读取该 Cookie(因此
//     注入的脚本无法窃取令牌);
//   - SameSite=Lax:对于来自其他站点的 POST,浏览器不会发送
//     该 Cookie。由于所有修改数据的操作都是
//     POST,其他站点上被动过手脚的页面无法冒充用户
//     预订或删除任何内容
//     (即所谓的 CSRF 攻击);
//   - Secure:在生产环境(HTTPS)中,Cookie 绝不会明文传输;
//   - MaxAge:Cookie 与令牌同时失效。
// =========================================================================

using System.Text;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.JsonWebTokens;
using Microsoft.IdentityModel.Tokens;
using RdvMedecins.Config;
using RdvMedecins.Entities;
using RdvMedecins.Repositories;

namespace RdvMedecins.Auth;

public class AuthService(UserRepository userRepository, IOptions<AuthOptions> options)
{
    // 承载令牌的 Cookie 的名称
    public const string JwtCookie = "rdvmedecins_jwt";

    private readonly AuthOptions auth = options.Value;

    // 令牌的签名密钥,由 appsettings.json 中的密钥
    // 生成。也用于验证令牌(参见 Program.cs)。
    public static SymmetricSecurityKey SigningKey(AuthOptions auth)
    {
        var bytes = Encoding.UTF8.GetBytes(auth.JwtSecret);
        if (bytes.Length < 32)
        {
            // HMAC-SHA256 需要至少 256 位的密钥:我们在启动时
            // 明确指出,而不是等到第一次登录
            throw new InvalidOperationException("Auth:JwtSecret must be at least 32 characters long (see appsettings.json).");
        }
        return new SymmetricSecurityKey(bytes);
    }

    // 如果登录名不存在或密码错误则为 null。
    // BCrypt.Verify 使用存储哈希中包含的"盐"对输入的密码
    // 进行哈希,然后比较两个结果。
    public async Task<User?> ValidateUserAsync(string login, string password)
    {
        var user = await userRepository.FindByLoginAsync(login);
        if (user is null)
        {
            return null;
        }
        return BCrypt.Net.BCrypt.Verify(password, user.Password) ? user : null;
    }

    // -----------------------------------------------------------------------
    // 构建 [user] 的 JWT 令牌并将其放入 Cookie。
    // 令牌经过签名(HMAC-SHA256),使用密钥:浏览器
    // 可以读取它(它没有加密),但不能修改它,任何
    // 修改都会使签名失效。
    // -----------------------------------------------------------------------
    public void SetToken(HttpResponse response, User user)
    {
        var descriptor = new SecurityTokenDescriptor
        {
            Claims = new Dictionary<string, object>
            {
                [JwtClaims.Sub] = user.Id,
                [JwtClaims.Login] = user.Login,
                [JwtClaims.Name] = user.Name,
                [JwtClaims.Role] = user.Role.ToString(),
            },
            Expires = DateTime.UtcNow.AddSeconds(auth.JwtExpiresInSeconds),
            SigningCredentials = new SigningCredentials(SigningKey(auth), SecurityAlgorithms.HmacSha256),
        };
        var token = new JsonWebTokenHandler().CreateToken(descriptor);

        response.Cookies.Append(JwtCookie, token, new CookieOptions
        {
            HttpOnly = true,
            SameSite = SameSiteMode.Lax,
            Secure = auth.CookieSecure,
            MaxAge = TimeSpan.FromSeconds(auth.JwtExpiresInSeconds),
            Path = "/",
        });
    }

    public static void ClearToken(HttpResponse response) =>
        response.Cookies.Delete(JwtCookie, new CookieOptions { Path = "/" });
}

下面对这段代码进行说明:

  • 第 38 行:该服务通过注入接收包含用户账户的 DAO([UserRepository],在讲解 DAO 层时已讨论)以及身份验证配置。[IOptions<AuthOptions>] 以 [Auth] 节的形式提供 [appsettings.json] 中的内容,类型为 [AuthOptions] 对象([Config] 文件夹):其 [Value] 属性包含密钥、令牌有效期以及 [CookieSecure] 选项。该服务在 [Scoped] 中注册于 [Program.cs],与它所使用的 DAO 一样(参见第 6 章);
  • 第 41 行:承载令牌的 Cookie 的名称;
  • 第 47–56 行:签名密钥(参见示例 25)。新特性:过短的密钥会被拒绝并抛出清晰的异常。该方法是 静态的:它只依赖其参数,并且在应用程序启动时由 [JwtAuthentication] (下一个文件)调用,此时还不存在任何服务。由于长度检查发生在这一时刻,错误的配置会阻止应用程序启动,而不是导致第一次登录失败;
  • 第 62–69 行:如果用户名和密码正确则返回账户;否则返回 [null] (参见示例 25)。该方法是异步的:账户查找是一次数据库查询(参见第 9 章);
  • 第 78–92 行:令牌,按示例 25 的方式生成。它包含账户标识符、用户名、导航栏中显示的名称以及角色;其有效期由配置决定(默认两小时);
  • 第 94–100 行:Cookie,使用示例 25 中的选项([HttpOnly]、[SameSite = Lax])以及另外两个选项:[Secure]在生产环境中启用(站点通过 [HTTPS] 提供服务),防止浏览器通过未加密的连接发送该 Cookie;[Path = "/"] 确保它随对站点的每个请求一起发送。[MaxAge] 会在令牌过期时删除该 Cookie;
  • 第 104–105 行:注销会删除 Cookie。为了让浏览器识别要删除的 Cookie,路径([Path])必须与存储位置的路径一致。该方法是静态的:处理程序 [JwtBearer](下一个文件)和异常过滤器 [HtmlExceptionFilter] (文件夹 [Web])也会用到它,它们没有可用的 [AuthService] 实例。

11.13.3. Auth/JwtAuthentication.cs

// =========================================================================
// Auth/JwtAuthentication.cs
// -------------------------------------------------------------------------
// JWT 令牌身份验证的配置,由
// Program.cs 调用(builder.Services.AddJwtAuthentication(...))。
//
// ASP.NET Core 的 JwtBearer "处理程序"在每个请求上所做的事情,
// 就是 NestJS 中 Passport 'jwt' 策略和 JwtAuthGuard 所做的:
//   1. 找到令牌;
//   2. 检查其签名和过期时间;
//   3. 由此得出用户(HttpContext.User,参见 ConnectedUser.cs)。
//
// 借助处理程序的"事件"(它在特定时刻调用的函数),
// 对 HTML 应用做三处调整:
//   - OnMessageReceived:从 COOKIE 中读取令牌,而不是
//     从 "Authorization: Bearer ..." 头中读取;
//   - OnChallenge:请求受保护页面但没有有效令牌时,
//     JwtBearer 会返回 401,这适合 JavaScript 客户端。
//     但浏览器必须被重定向回登录页面;
//   - (403:角色不足)这里无需处理:空的 403 响应
//     由 UseStatusCodePagesWithReExecute 转为错误页面
//     (参见 Program.cs 和 Controllers/ErrorController.cs)。
// =========================================================================

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using RdvMedecins.Config;
using RdvMedecins.Web;

namespace RdvMedecins.Auth;

public static class JwtAuthentication
{
    public static IServiceCollection AddJwtAuthentication(this IServiceCollection services, AuthOptions auth)
    {
        services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                // 我们保持令牌的声明名称不变("role"、"sub"……),
                // 而不是将其转换为微软风格的长名称
                options.MapInboundClaims = false;

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = AuthService.SigningKey(auth),
                    ValidateLifetime = true,
                    // 过期的令牌会被立即拒绝(默认情况下,
                    // 会容忍 5 分钟的时钟差异)
                    ClockSkew = TimeSpan.Zero,
                    // 我们的令牌既没有签发者(iss)也没有受众(aud)
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    // 哪个声明包含名称,哪个包含角色:
                    // [Authorize(Roles = "ADMIN")] 比较的是 "role" 声明
                    NameClaimType = JwtClaims.Name,
                    RoleClaimType = JwtClaims.Role,
                };

                options.Events = new JwtBearerEvents
                {
                    // 1. 令牌在 Cookie 中
                    OnMessageReceived = context =>
                    {
                        context.Token = context.Request.Cookies[AuthService.JwtCookie];
                        return Task.CompletedTask;
                    },

                    // 2. 没有有效令牌的受保护页面 -> 登录页面
                    OnChallenge = context =>
                    {
                        // HandleResponse():"由我负责响应",因此 JwtBearer
                        // 不会写入它的 401
                        context.HandleResponse();
                        // Cookie 存在但已失效:会话已过期
                        if (context.Request.Cookies.ContainsKey(AuthService.JwtCookie))
                        {
                            AuthService.ClearToken(context.Response);
                            Flash.Put(context.HttpContext, FlashType.Danger, "ERRORS.SESSION_EXPIRED");
                        }
                        context.Response.Redirect("/login");
                        return Task.CompletedTask;
                    },
                };
            });

        return services;
    }
}

在示例 25 中,[JwtBearer] 的配置写在 [Program.cs] 中。这里,它存放在一个扩展方法中,[Program.cs] 只用一行调用它:[builder.Services.AddJwtAuthentication(authOptions)]。下面对这段代码进行说明:

  • 第 32–34 行:扩展方法(参见示例 06)。它直接接收一个 [AuthOptions] 对象,该对象由 [Program.cs] 从配置中读取:注册服务时,依赖注入尚不可用,因此我们无法请求 [IOptions<AuthOptions>];
  • 第 37–42 行:身份验证方案 [JwtBearer],其中存储了令牌的声明名称(参见示例 25);
  • 第 44–54 行:对每个令牌执行的检查:使用由 [AuthService.SigningKey] 生成的密钥验证签名,以及过期时间。相对于示例 25 的新特性:[ClockSkew = TimeSpan.Zero]。默认情况下,[JwtBearer] 在令牌过期后的五分钟内仍然接受它,以兼顾生成令牌的服务器与验证令牌的服务器之间时钟的轻微差异。这里是同一台服务器:过期的令牌会被立即拒绝;
  • 第 57–58 行:声明 [name] 对应 [User.Identity.Name],声明 [role] 是由 [[Authorize(Roles = "ADMIN")]] 和 [User.IsInRole] 验证的那一个(参见示例 26);
  • 第 64–67 行:令牌是从 Cookie 中读取的,而不是从 [Authorization] 标头中读取(参见示例 25);
  • 第 71–82 行:在没有有效令牌的情况下请求受保护的页面,会重定向到登录页面(参见示例 25)。新特性(第 77–80 行):如果请求中包含令牌 Cookie,就意味着用户曾经登录过,但其令牌已过期(或被篡改)。我们删除这个已经无用的 Cookie,并显示一条闪现消息(参见示例 20;[Flash] 类将在讲解 [Web] 文件夹时讨论):登录页面会显示“您的会话已过期”,而不是让用户疑惑自己为什么会来到这里。该消息是一个翻译键(参见示例 22)。

403 Forbidden 响应(角色不足)不需要事件:与示例 26 中一样,空响应会由 [UseStatusCodePagesWithReExecute] 转换为错误页面。在 [NestJS] 项目中,这项任务由 [Passport] 和 [jwt] 策略(读取并验证令牌)、守卫 [JwtAuthGuard] (要求令牌)和异常过滤器(将拒绝转换为重定向)分担;而在这里,处理程序 [JwtBearer]、它的事件以及特性 [[Authorize]] 就足够了。

11.13.4. Auth/InvalidSessionException.cs

// =========================================================================
// Auth/InvalidSessionException.cs
// -------------------------------------------------------------------------
// 令牌有效,但它所指向的账户已不存在:
// 登录之后它已被删除(由患者本人在另一个
// 标签页中,或由 ADMIN 删除)。我们将这种情况视为会话过期:
// HtmlExceptionFilter 清除 Cookie 并重定向到登录页面
// (相当于 NestJS 的 UnauthorizedException)。
// =========================================================================

namespace RdvMedecins.Auth;

public class InvalidSessionException() : Exception("the account of the connected user no longer exists");
  • 第 13 行:令牌可能是有效的(签名正确、未过期),即使它所指向的账户在登录之后已被删除。患者的页面通过查找与该账户关联的客户(文件 [ConnectedPatientAsync] 中的方法 [Web/Utils.cs])来检测这种情况,然后抛出此异常;异常过滤器 [HtmlExceptionFilter] (过滤器参见示例 24)会拦截它,删除 Cookie,并重定向到登录页面,同时显示“会话已过期”消息。该类有一个无参数的主构造函数,它将其消息传递给父类 [Exception] 的构造函数。

11.13.5. Auth/CaptchaService.cs

// =========================================================================
// Auth/CaptchaService.cs
// -------------------------------------------------------------------------
// 由服务器自身生成的验证码(CAPTCHA,"区分人类与机器人的测试"),
// 不依赖任何外部服务:几个扭曲的字符,
// 被线条干扰,放在一张 SVG 图像中。人类读起来
// 毫无困难;而只会循环发送表单的机器人
// 做不到。
//
// NestJS 项目使用了 svg-captcha 库。这里不使用
// 任何库:图像由 CaptchaDrawing 类(见下文)根据
// 一套手写的小型矢量"字体"绘制。一个重要
// 的点:每个字符都用笔画(<path>)绘制,绝不
// 写成文本(<text>),否则机器人只需读取图像的
// 源代码。
//
// 工作方式:
//   1. Generate() 绘制一段随机文本,将其转为图像,并把
//      正确答案存放在服务器内存中,对应一个随机标识符;
//   2. 页面显示图像,并把标识符放入表单的隐藏字段
//      (答案本身绝不离开服务器);
//   3. Verify(id, input) 将输入与预期答案比较,然后
//      忘记该验证码:每张图像只能使用一次,机器人无法
//      重放已经找到的答案。
//
// 单例服务(整个服务器只有一个实例,参见
// Program.cs),被多个请求并行使用:
// 因此使用 ConcurrentDictionary,这是一种多个线程可以同时读取
// 和修改而不会损坏的字典。
//
// 可接受的局限:仅限单个进程的内存。如果有多台服务器
// 位于负载均衡器之后,就需要共享存储。
// =========================================================================

using System.Collections.Concurrent;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;

namespace RdvMedecins.Auth;

// Id:放入表单隐藏的 "captchaId" 字段
// Svg:图像,原样插入页面
public record Captcha(string Id, string Svg);

public class CaptchaService
{
    // 图像的有效期:你有 10 分钟来填写表单
    private static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(10);

    // 内存保护:超过此数量后,我们会忘记最旧的验证码
    private const int MaxCaptchas = 10_000;

    // id -> (预期答案,过期时间)
    private readonly ConcurrentDictionary<string, (string Text, DateTime Expires)> pending = new();

    public Captcha Generate()
    {
        Purge();
        var text = CaptchaDrawing.RandomText(5); // 5 个字符
        var id = Guid.NewGuid().ToString();
        pending[id] = (text, DateTime.UtcNow + Lifetime);
        return new Captcha(id, CaptchaDrawing.Svg(text));
    }

    // 如果 [input] 是验证码 [id] 的正确答案则为 true(不区分
    // 大小写)。无论如何,验证码都会被消耗。
    // TryRemove 是原子的:如果两个请求同时出示同一个验证码,
    // 只有一个能将其移除,另一个会失败。
    public bool Verify(string? id, string? input)
    {
        if (id is null || input is null || !pending.TryRemove(id, out var expected))
        {
            return false;
        }
        return expected.Expires > DateTime.UtcNow
            && string.Equals(expected.Text, input.Trim(), StringComparison.OrdinalIgnoreCase);
    }

    private void Purge()
    {
        var now = DateTime.UtcNow;
        foreach (var (id, captcha) in pending)
        {
            if (captcha.Expires <= now || pending.Count >= MaxCaptchas)
            {
                pending.TryRemove(id, out _);
            }
        }
    }
}

// -------------------------------------------------------------------------
// SVG 图像的绘制(150 x 50 像素)。
// -------------------------------------------------------------------------
internal static class CaptchaDrawing
{
    private const int Width = 150;
    private const int Height = 50;

    // "字体":每个字符是一组笔画,每个笔画是
    // 4 x 6 网格中的一系列点(x, y)(y 向下)。
    // 太容易相互混淆的字符:已排除(0 O、1 I L)。
    private static readonly Dictionary<char, double[][]> Font = new()
    {
        ['A'] = [[0, 6, 2, 0, 4, 6], [0.8, 3.8, 3.2, 3.8]],
        ['B'] = [[0, 0, 0, 6, 3, 6, 4, 5, 4, 4, 3, 3, 0, 3], [0, 0, 3, 0, 4, 1, 4, 2, 3, 3]],
        ['C'] = [[4, 1, 3, 0, 1, 0, 0, 1, 0, 5, 1, 6, 3, 6, 4, 5]],
        ['D'] = [[0, 0, 0, 6, 2.5, 6, 4, 4.5, 4, 1.5, 2.5, 0, 0, 0]],
        ['E'] = [[4, 0, 0, 0, 0, 6, 4, 6], [0, 3, 3, 3]],
        ['F'] = [[4, 0, 0, 0, 0, 6], [0, 3, 3, 3]],
        ['G'] = [[4, 1, 3, 0, 1, 0, 0, 1, 0, 5, 1, 6, 3, 6, 4, 5, 4, 3.5, 2.5, 3.5]],
        ['H'] = [[0, 0, 0, 6], [4, 0, 4, 6], [0, 3, 4, 3]],
        ['J'] = [[4, 0, 4, 5, 3, 6, 1, 6, 0, 5]],
        ['K'] = [[0, 0, 0, 6], [4, 0, 0, 3.5], [1.3, 2.6, 4, 6]],
        ['M'] = [[0, 6, 0, 0, 2, 3.5, 4, 0, 4, 6]],
        ['N'] = [[0, 6, 0, 0, 4, 6, 4, 0]],
        ['P'] = [[0, 6, 0, 0, 3, 0, 4, 1, 4, 2, 3, 3, 0, 3]],
        ['Q'] = [[1, 0, 3, 0, 4, 1, 4, 5, 3, 6, 1, 6, 0, 5, 0, 1, 1, 0], [2.5, 4.5, 4, 6.3]],
        ['R'] = [[0, 6, 0, 0, 3, 0, 4, 1, 4, 2, 3, 3, 0, 3], [2, 3, 4, 6]],
        ['S'] = [[4, 1, 3, 0, 1, 0, 0, 1, 0, 2, 1, 3, 3, 3, 4, 4, 4, 5, 3, 6, 1, 6, 0, 5]],
        ['T'] = [[0, 0, 4, 0], [2, 0, 2, 6]],
        ['U'] = [[0, 0, 0, 5, 1, 6, 3, 6, 4, 5, 4, 0]],
        ['V'] = [[0, 0, 2, 6, 4, 0]],
        ['W'] = [[0, 0, 1, 6, 2, 2.5, 3, 6, 4, 0]],
        ['X'] = [[0, 0, 4, 6], [4, 0, 0, 6]],
        ['Y'] = [[0, 0, 2, 3, 4, 0], [2, 3, 2, 6]],
        ['Z'] = [[0, 0, 4, 0, 0, 6, 4, 6]],
        ['2'] = [[0, 1, 1, 0, 3, 0, 4, 1, 4, 2, 0, 6, 4, 6]],
        ['3'] = [[0, 1, 1, 0, 3, 0, 4, 1, 4, 2, 3, 3, 1.5, 3], [3, 3, 4, 4, 4, 5, 3, 6, 1, 6, 0, 5]],
        ['4'] = [[3, 6, 3, 0, 0, 4, 4, 4]],
        ['5'] = [[4, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 5, 3, 6, 1, 6, 0, 5]],
        ['6'] = [[4, 1, 3, 0, 1, 0, 0, 1, 0, 5, 1, 6, 3, 6, 4, 5, 4, 4, 3, 3, 0, 3]],
        ['7'] = [[0, 0, 4, 0, 1.5, 6]],
        ['8'] = [[1, 3, 0, 2, 0, 1, 1, 0, 3, 0, 4, 1, 4, 2, 3, 3, 1, 3, 0, 4, 0, 5, 1, 6, 3, 6, 4, 5, 4, 4, 3, 3]],
        ['9'] = [[4, 3, 1, 3, 0, 2, 0, 1, 1, 0, 3, 0, 4, 1, 4, 5, 3, 6, 1, 6, 0, 5]],
    };

    private static readonly char[] Alphabet = [.. Font.Keys];

    // 几种深色,在浅色背景上易于阅读
    private static readonly string[] Colors = ["#1f4e79", "#7b2d26", "#2e6b30", "#5b2c83", "#8a5a00", "#23395d", "#9c2a5b"];

    // RandomNumberGenerator:"加密级"随机数生成器,
    // 不可预测(不同于 Random,其序列可能被猜出)
    public static string RandomText(int length) =>
        new(Enumerable.Range(0, length).Select(_ => Alphabet[RandomNumberGenerator.GetInt32(Alphabet.Length)]).ToArray());

    private static double RandomBetween(double min, double max) =>
        min + (max - min) * RandomNumberGenerator.GetInt32(1_000_001) / 1_000_000.0;

    public static string Svg(string text)
    {
        var svg = new StringBuilder();
        svg.Append($"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{Width}\" height=\"{Height}\" viewBox=\"0 0 {Width} {Height}\">");
        svg.Append($"<rect width=\"100%\" height=\"100%\" fill=\"#f5f7fa\"/>");

        // 字符:每个都被放大、倾斜、平移,且每个点
        // 都随机轻微移动
        var step = (Width - 20) / (double)text.Length;
        for (var i = 0; i < text.Length; i++)
        {
            var scale = RandomBetween(4.6, 5.6); // 网格单位的大小,以像素计
            var angle = RandomBetween(-0.35, 0.35); // 旋转,以弧度计(约 ±20°)
            var cx = 10 + step * (i + 0.5) + RandomBetween(-3, 3); // 字符的中心
            var cy = Height / 2.0 + RandomBetween(-4, 4);
            var color = Colors[RandomNumberGenerator.GetInt32(Colors.Length)];
            var d = new StringBuilder();
            foreach (var stroke in Font[text[i]])
            {
                for (var k = 0; k < stroke.Length; k += 2)
                {
                    // 网格点,以 (2, 3) 为中心,经过扭曲、旋转、放置
                    var x = (stroke[k] - 2 + RandomBetween(-0.2, 0.2)) * scale;
                    var y = (stroke[k + 1] - 3 + RandomBetween(-0.2, 0.2)) * scale;
                    var px = cx + x * Math.Cos(angle) - y * Math.Sin(angle);
                    var py = cy + x * Math.Sin(angle) + y * Math.Cos(angle);
                    d.Append(k == 0 ? 'M' : 'L').Append(Number(px)).Append(' ').Append(Number(py)).Append(' ');
                }
            }
            svg.Append($"<path d=\"{d.ToString().TrimEnd()}\" fill=\"none\" stroke=\"{color}\" stroke-width=\"{Number(RandomBetween(2.2, 3))}\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>");
        }

        // 3 条干扰线:穿过图像的曲线
        for (var n = 0; n < 3; n++)
        {
            var color = Colors[RandomNumberGenerator.GetInt32(Colors.Length)];
            svg.Append($"<path d=\"M{Number(RandomBetween(0, 20))} {Number(RandomBetween(5, 45))} " +
                       $"C{Number(RandomBetween(30, 60))} {Number(RandomBetween(0, 50))} {Number(RandomBetween(90, 120))} {Number(RandomBetween(0, 50))} " +
                       $"{Number(RandomBetween(130, 150))} {Number(RandomBetween(5, 45))}\" fill=\"none\" stroke=\"{color}\" stroke-width=\"1.3\"/>");
        }

        svg.Append("</svg>");
        return svg.ToString();
    }

    // 带小数点的数字,无论服务器的语言是什么
    // (在法语中,ToString() 会写成 "12,5",SVG 无法读取)
    private static string Number(double value) => value.ToString("0.#", CultureInfo.InvariantCulture);
}

该文件包含两个类:服务类,除了一项保护措施之外与示例 27 中的完全相同;以及生成图像的 [CaptchaDrawing] 类,它已在示例 27 中讨论过(文件 [Auth/CaptchaDrawing.cs])。我们来看这段代码:

  • 第 44 行:页面所接收到的验证码(CAPTCHA):标识符(放置在隐藏的表单字段中)和 [SVG] 图像;
  • 第 49–52 行:图像的有效期为十分钟,并且对待处理验证码的数量设有上限。每次显示登录页面时,都会在内存中添加一个验证码;如果没有上限,一个数百万次请求该页面却从不作答的机器人最终会耗尽服务器的内存;
  • 第 55 行:id → (预期答案,过期时间)。这一对是一个 元组 ,其元素带有名称([Text]、[Expires])。该服务是单例,被并发请求使用:因此使用 [ConcurrentDictionary] (参见示例 27);
  • 第 57–63 行:先清理,然后生成随机的五个字符的文本字符串,以随机标识符([Guid.NewGuid()],无法猜测)存储,并显示出来;
  • 第 70–77 行:验证,与示例 27 中相同:验证码在任何情况下都会被消耗([TryRemove]),然后系统验证它是否未过期,以及输入的文本(去掉空格后)是否正确,不区分大小写。[TryRemove] 是 原子的:如果两个请求同时提交同一个验证码,只有一个能将其移除;
  • 第 80–87 行:过期的验证码被丢弃;如果达到上限,有效的验证码也会被移除,直到数量降到上限以下。[ConcurrentDictionary] 可以在遍历的同时被修改,而标准的 [Dictionary] 不允许这样做(参见下文的 [AttemptLimiterService])。然而,它不保留插入顺序:以这种方式移除的验证码不一定是最旧的,而 [NestJS] 项目中的 [Map] 则可以先移除最旧的。这种情况只会在遭受攻击时出现:近似处理就足够了;
  • 第 96 行:绘制图像。[internal]:该类仅在应用程序内部可见;
  • 第 104–136 行:“字体”:对每个字符,给出一组笔画,每个笔画是 4 × 6 网格中的一系列 (x, y) 坐标。方括号 [[...]] 是 集合表达式 ([C#] 12),一种紧凑的数组表示法;
  • 第 139 行:可用的字符,即字体的键。[..] 将 一个集合展开到另一个集合中;
  • 第 146–147 行和第 149–150 行:随机化使用 [RandomNumberGenerator],这是一个密码学生成器,其输出不可预测;
  • 第 152–194 行:图像是一段 [SVG] 文本,由 [StringBuilder] (一种在添加元素时无需每次重写而可以不断扩展的字符串)组装而成。每个字符(第 160–181 行)变成一条 [<path>] 路径:网格上的每个点都会被轻微偏移、放大、旋转,并放置到图像中的相应位置,同时随机选择颜色和线条粗细。这些字符是线条,而不是文本:机器人无法在图像的代码中读取它们。随后有三条干扰曲线穿过图像(第 185–190 行);
  • 第 199 行:[SVG] 中的数字使用小数点书写。[CultureInfo.InvariantCulture] 无论服务器使用何种语言都强制采用这种写法:在法语中,[ToString()] 会使用逗号(参见第 5 章)。

11.13.6. Auth/AttemptLimiterService.cs

// =========================================================================
// Auth/AttemptLimiterService.cs
// -------------------------------------------------------------------------
// 对抗机器人的第二道防线(第一道是验证码):我们统计
// 尝试次数,超过阈值就封锁一段时间。
//
//   - 登录:同一 IP 地址对同一登录名失败 LoginMaxFailures 次
//     (验证码错误或密码错误)后,该组合
//     被封锁 LoginBlockMinutes 分钟。如果同一 IP 地址
//     累计失败达到 5 倍(所有登录名合计),也会被
//     封锁(机器人尝试成千上万个不同的登录名);
//   - 创建账户:同一 IP 地址每小时最多
//     创建 RegistrationMaxPerHour 个账户。
//
// 注意在教室中:所有计算机通常通过同一个 IP 地址
// 访问互联网。因此登录封锁首先针对(IP,登录名)
// 组合,输错密码的学生不会
// 封锁邻座的同学,而且阈值可以在
// appsettings.json 中调整("Protection" 节)。
//
// 单例服务,被并行请求调用:对计数器的所有
// 操作都在锁下进行,从而保证
// 同一时间只有一个线程读取并修改计数器。
// =========================================================================

using Microsoft.Extensions.Options;
using RdvMedecins.Config;

namespace RdvMedecins.Auth;

public class AttemptLimiterService(IOptions<ProtectionOptions> options)
{
    private class Counter
    {
        public int Count; // 当前窗口内统计的尝试次数
        public DateTime Start; // 计数窗口的开始时间
        public DateTime BlockedUntil; // 未被封锁时为 DateTime.MinValue
    }

    private static readonly TimeSpan OneHour = TimeSpan.FromHours(1);

    private readonly Dictionary<string, Counter> counters = [];
    private readonly Lock syncLock = new(); // .NET 9+ 的 Lock 类型,专为 "lock" 设计

    private readonly int maxLoginFailures = options.Value.LoginMaxFailures;
    private readonly TimeSpan loginBlockDuration = TimeSpan.FromMinutes(options.Value.LoginBlockMinutes);
    private readonly int maxRegistrations = options.Value.RegistrationMaxPerHour;

    // 登录

    // 剩余封锁分钟数(0 = 允许尝试)
    public int LoginBlockMinutes(string ip, string login)
    {
        lock (syncLock)
        {
            return Math.Max(RemainingMinutes(LoginKey(ip, login)), RemainingMinutes(IpKey(ip)));
        }
    }

    public void LoginFailure(string ip, string login)
    {
        lock (syncLock)
        {
            Count(LoginKey(ip, login), maxLoginFailures, loginBlockDuration, loginBlockDuration);
            Count(IpKey(ip), maxLoginFailures * 5, loginBlockDuration, loginBlockDuration);
        }
    }

    // 登录成功会重置此登录名的计数器
    public void LoginSuccess(string ip, string login)
    {
        lock (syncLock)
        {
            counters.Remove(LoginKey(ip, login));
        }
    }

    // 注册

    public int RegistrationBlockMinutes(string ip)
    {
        lock (syncLock)
        {
            return RemainingMinutes($"registration|{ip}");
        }
    }

    // 一小时窗口;一旦达到配额,就封锁到该小时结束
    public void RegistrationSuccess(string ip)
    {
        lock (syncLock)
        {
            Count($"registration|{ip}", maxRegistrations, OneHour, OneHour);
        }
    }

    // 共享机制
    // (私有方法总是在锁下调用)

    private int RemainingMinutes(string key)
    {
        if (!counters.TryGetValue(key, out var c))
        {
            return 0;
        }
        var remaining = c.BlockedUntil - DateTime.UtcNow;
        return remaining > TimeSpan.Zero ? (int)Math.Ceiling(remaining.TotalMinutes) : 0;
    }

    // 统计一次尝试;如果在窗口内达到阈值,则封锁
    private void Count(string key, int max, TimeSpan window, TimeSpan block)
    {
        var now = DateTime.UtcNow;
        Purge(now);
        if (!counters.TryGetValue(key, out var c) || now - c.Start > window)
        {
            c = new Counter { Count = 0, Start = now, BlockedUntil = DateTime.MinValue };
            counters[key] = c;
        }
        c.Count++;
        if (c.Count >= max)
        {
            c.BlockedUntil = now + block;
            c.Count = 0; // 封锁结束后,从零重新开始
            c.Start = c.BlockedUntil;
        }
    }

    // 我们忘记不再有用的计数器(既未被封锁,也不是最近的)
    private void Purge(DateTime now)
    {
        if (counters.Count < 1000)
        {
            return;
        }
        foreach (var (key, c) in counters.ToList())
        {
            if (c.BlockedUntil < now && now - c.Start > OneHour)
            {
                counters.Remove(key);
            }
        }
    }

    private static string LoginKey(string ip, string login) => $"login|{ip}|{login.Trim().ToLowerInvariant()}";

    private static string IpKey(string ip) => $"ip|{ip}";
}

与示例 27 相比,限制器保护两个操作(登录和账户创建);登录封锁作用于(IP 地址,登录名)这一对,并且阈值可在 [appsettings.json] 中配置。我们来分析这段代码:

  • 第 31 行:[IOptions<ProtectionOptions>] 指定 [Protection] 节,来自 [appsettings.json] (文件夹 [Config]):允许的登录失败次数(默认 5 次)、锁定时长(15 分钟)以及每小时创建的账户数(10 个);
  • 第 33–37 行:计数器:尝试次数、计数窗口的起点,以及锁定的结束时间(如果没有锁定,则为 [DateTime.MinValue],即最早的可能日期)。这是一个 嵌套的私有类:它只为这个服务而存在。它是类,而不是 [record] 或结构:从字典中读取的计数器会被原地修改;
  • 第 42–43 行:一个普通的 [Dictionary],由锁保护(参见示例 27)。[ConcurrentDictionary] 是不够的:统计一次尝试需要读取计数器、修改它,并可能替换它,而这整个操作序列必须在不被其他请求打断的情况下执行。因此,每个公共方法都在 [lock (syncLock)] 块中执行其任务;
  • 第 45–47 行:阈值,一次性读取。主构造函数的参数可以用来初始化字段;
  • 第 52–56 行:连接尝试的剩余锁定时间:两种可能的锁定时长中较长的一个,即(IP 地址,登录名)这一对的锁定时长与单独 IP 地址的锁定时长;
  • 第 60–65 行:一次失败的尝试会被计两次。对于(IP 地址,登录名)这一对:使用同一登录名连续失败五次,会封锁该登录名,但仅限于该地址。对于单独的 IP 地址,阈值提高到五倍:尝试大量不同登录名的机器人也会被封锁。在教室里,所有计算机通常通过同一个 IP 地址连接互联网:输错密码的学生不应该封锁他们的邻座,因此才按“对”进行封锁;
  • 第 70–74 行:成功登录会重置该特定登录名的计数器(而不是 IP 地址的计数器);
  • 第 80–84 行和第 89–93 行:对于账户创建,只统计成功的尝试:同一个 IP 地址每小时最多创建十个账户。达到配额后,该地址被封锁一小时;
  • 第 100–107 行:封锁的剩余分钟数,向上取整([Math.Ceiling]):当还剩 20 秒时,显示“1 分钟”而不是“0 分钟”。这些私有方法不获取锁:它们总是由已经持有锁的公共方法调用;
  • 第 111–125 行:计数。未知的键,或其计数窗口已过期的键,从新的计数器开始。达到阈值时,该键被锁定,并在锁定结束时从零重新开始计数;
  • 第 130–140 行:清理不再需要的计数器(既未被锁定也不是最近的),仅在字典超过 1000 个条目时执行。我们遍历条目的一个副本([ToList()]):[Dictionary] 在被遍历时不能被修改;
  • 第 145–147 行:生成字典的键。去掉登录名中的空格并将其转换为小写:[Admin] 和 [admin] 共用同一个计数器;机器人无法通过改变大小写来绕过锁定。

11.13.7. Auth/RegistrationPassService.cs

// =========================================================================
// Auth/RegistrationPassService.cs
// -------------------------------------------------------------------------
// 创建账户的"通行证"。
//
// 要打开"创建患者账户"页面,必须先
// 复制身份验证页面的验证码(参见
// RegistrationController,POST /register/access)。然后服务器会颁发
// 一个通行证:
//   - 一个随机标识符,存放在 HttpOnly Cookie 中;
//   - 有效期 15 分钟(足够填写表单,即使输入错误后
//     需要多次尝试);
//   - 一旦创建了账户即被消耗:一个已解决的验证码最多对应一个账户。
//     机器人无法批量创建账户。
//
// 没有有效通行证时,GET 和 POST /register 会重定向回
// 身份验证页面:直接输入 /register 网址并不能
// 绕过验证码。
//
// 与验证码一样,通行证存放在进程的内存中。
// =========================================================================

using System.Collections.Concurrent;

namespace RdvMedecins.Auth;

public class RegistrationPassService
{
    public const string Cookie = "rdvmedecins_registration";

    private static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(15);
    private const int MaxPasses = 10_000;

    // id -> 过期时间
    private readonly ConcurrentDictionary<string, DateTime> passes = new();

    // 颁发一个新通行证;返回其标识符
    public string Issue()
    {
        Purge();
        var id = Guid.NewGuid().ToString();
        passes[id] = DateTime.UtcNow + Lifetime;
        return id;
    }

    // 如果 [id] 是存在且未过期的通行证则为 true
    public bool IsValid(string? id) =>
        id is not null && passes.TryGetValue(id, out var expires) && expires > DateTime.UtcNow;

    // 通行证已被使用:我们忘记它
    public void Consume(string? id)
    {
        if (id is not null)
        {
            passes.TryRemove(id, out _);
        }
    }

    // 浏览器仅向 /register... 地址发送该 Cookie
    public static CookieOptions GetCookieOptions() => new()
    {
        HttpOnly = true,
        SameSite = SameSiteMode.Lax,
        MaxAge = Lifetime,
        Path = "/register",
    };

    private void Purge()
    {
        var now = DateTime.UtcNow;
        foreach (var (id, expires) in passes)
        {
            if (expires <= now || passes.Count >= MaxPasses)
            {
                passes.TryRemove(id, out _);
            }
        }
    }
}

只要解决了验证码,就可以从登录页面创建客户账户。注册表单通过后续请求来显示和提交:这些请求必须知道之前的某个请求已成功解决了验证码。这就是通行码的作用,它由 [RegistrationController] (在控制器部分说明)签发和验证:

  • 第 29 行:承载通行码的 Cookie 的名称;
  • 第 31–35 行:通行码的有效期为十五分钟;待处理的通行码与验证码一样保存在内存中,并具有相同的时间限制;
  • 第 38–43 行:通行码是一个随机标识符,与其过期时间一起存储;控制器将它放入 Cookie 中;
  • 第 47–48 行:只有持有有效的通行码,才会显示并接受注册表单。验证不会消耗通行码(使用 [TryGetValue],而不是 [TryRemove]):如果用户输入有误,可以多次重新提交表单;
  • 第 51–55 行:创建账户会消耗通行码:解决一次验证码只有权创建一个账户,不能更多;
  • 第 60–65 行:Cookie 选项。[new()] 创建方法所声明类型([CookieOptions])的对象。选项 [Path = "/register"] 将 Cookie 的发送限制在以 [/register] 开头的 URL:其他请求不会无谓地携带它;
  • 第 68–75 行:清理过程,与验证码的清理过程相同。

11.13.8. Controllers/AuthController.cs

// =========================================================================
// Controllers/AuthController.cs
// -------------------------------------------------------------------------
// 登录的无保护路由:
//   GET / 重定向到该角色的主页(或 /login)
//   GET /login 显示登录表单(含验证码)
//   POST /login 检查尝试次数限制、验证码、登录名 / 密码
//   POST /logout 清除令牌 Cookie
//
// MVC 控制器继承自 Controller,并返回 IActionResult:
// View(...) 用于显示页面,Redirect(...) 用于重定向……
// [HttpGet("login")] / [HttpPost("login")]:"特性路由",
// 相当于 @Get('login') / @Post('login')。
//
// 对抗机器人的保护,按以下顺序:
//   1. 该 IP 地址对此登录名最近失败次数过多?
//      -> 立即拒绝,甚至不看密码;
//   2. 验证码答案错误?-> 拒绝(计为一次失败);
//   3. 只有此时才验证密码。
// 我们绝不检查在第 1 或第 2 步被拒绝的尝试的密码:
// 因此机器人坚持尝试也学不到任何东西。
// =========================================================================

using Microsoft.AspNetCore.Mvc;
using RdvMedecins.Auth;
using RdvMedecins.Entities;
using RdvMedecins.Models;

namespace RdvMedecins.Controllers;

public class AuthController(
    AuthService authService,
    CaptchaService captchaService,
    AttemptLimiterService limiter) : Controller
{
    // 每个角色在登录后立即进入的主页
    public static string HomePage(Role role) => role == Role.USER ? "/my-area" : "/schedule";

    [HttpGet("/")]
    public IActionResult Home()
    {
        // User:请求的用户,由身份验证中间件根据令牌重建
        // (参见 Auth/ConnectedUser.cs)
        var user = User.CurrentUser();
        return Redirect(user is not null ? HomePage(user.Role) : "/login");
    }

    // GET /login[?login=xxx]:可选参数预填登录
    // 字段(在创建账户之后立即使用,参见 RegistrationController)
    [HttpGet("login")]
    public IActionResult ShowLogin(string? login)
    {
        // 已登录(令牌仍然有效):直接进入主页
        var user = User.CurrentUser();
        if (user is not null)
        {
            return Redirect(HomePage(user.Role));
        }
        return Form(login is null ? "" : login[..Math.Min(login.Length, 30)]);
    }

    // 操作的参数由同名的表单字段填充
    // (模型绑定);[FromForm] 指定从
    // POST 请求的正文中查找它们
    [HttpPost("login")]
    public async Task<IActionResult> LogIn(
        [FromForm] string? login,
        [FromForm] string? password,
        [FromForm] string? captchaId,
        [FromForm] string? captcha)
    {
        login = (login ?? "").Trim();
        password ??= "";
        var ip = IpAddress(HttpContext);

        // 1. 最近失败次数过多?
        var minutes = limiter.LoginBlockMinutes(ip, login);
        if (minutes > 0)
        {
            return Form(login, "ERRORS.TOO_MANY_ATTEMPTS", new Dictionary<string, string> { ["minutes"] = minutes.ToString() });
        }

        // 2. 验证码
        if (!captchaService.Verify(captchaId, captcha))
        {
            limiter.LoginFailure(ip, login);
            return Form(login, "ERRORS.WRONG_CAPTCHA");
        }

        // 3. 密码
        var user = login != "" && password != "" ? await authService.ValidateUserAsync(login, password) : null;
        if (user is null)
        {
            limiter.LoginFailure(ip, login);
            return Form(login, "LOGIN.ERROR");
        }

        limiter.LoginSuccess(ip, login);
        authService.SetToken(Response, user);
        return Redirect(HomePage(user.Role));
    }

    // 使用 POST 注销(而不是简单的 GET 链接):第三方站点无法
    // 在用户不知情的情况下使其注销(参见 SameSite、AuthService)
    [HttpPost("logout")]
    public IActionResult LogOut()
    {
        AuthService.ClearToken(Response);
        return Redirect("/login");
    }

    // 访问者的 IP 地址。在反向代理(nginx 等)之后,必须启用
    // UseForwardedHeaders 中间件,才能得到访问者的
    // 地址而不是代理的地址。
    public static string IpAddress(HttpContext http) => http.Connection.RemoteIpAddress?.ToString() ?? "unknown";

    // 表单,总是带有新的验证码(每张图像只使用一次)
    private ViewResult Form(string login, string? error = null, IReadOnlyDictionary<string, string>? errorParams = null) =>
        View("Login", new LoginModel
        {
            PageTitle = "LOGIN.TITLE",
            Login = login, // 我们重新显示输入的登录名,绝不显示密码
            Captcha = captchaService.Generate(),
            Error = error,
            ErrorParams = errorParams,
        });
}

下面对这段代码进行说明:

  • 第 31–34 行:控制器接收它所需的三个服务。没有 [[Authorize]] 特性:其页面无需登录即可访问;
  • 第 37 行:主页取决于角色:患者为“我的空间”,其他人为日历;
  • 第 39–45 行:站点根路径会重定向到与角色对应的主页或登录页面。身份验证中间件对 所有 请求都会运行,无论请求是否受保护:如果 Cookie 中包含有效的令牌,则 [User] 会被填充,即使在这里也是如此。相比之下,[NestJS] 项目必须自己验证令牌(方法 [readToken]),因为此路由不应用令牌检查;
  • 第 50–59 行:已登录的用户会被重定向到其主页。可选参数 [login] 来自 URL(参见示例 07),在创建账户后用于预填该字段。[login[..n]] (范围运算符)保留前 [n] 个字符:其长度被限制为 30,因为来自请求的数据绝不能不加防范地使用;
  • 第 65–70 行:登录表单的字段(参见示例 11),包括通过隐藏字段传递的验证码标识符,以及用户的输入。它们都声明为 [string?]:缺失的字段得到 [null],由操作来决定如何处理它;
  • 第 72–74 行:缺失的登录名变为空字符串;[password ??= ""] 只有在 [password] 为 [null] 时才会影响空字符串;
  • 第 77–80 行:1. 被封锁的“对”根本不会被处理:既不检查验证码,也不检查密码。错误是一个带有一个参数的翻译键:需要等待的分钟数;
  • 第 84–87 行:2. 验证码。验证码错误算作一次失败(参见示例 27);
  • 第 91–95 行:3. 然后才检查密码。空的用户名或密码不会进行计算开销很大的 [bcrypt] 计算。用户名未知或密码错误:给出同样刻意含糊的消息(参见示例 25),并再记一次失败;
  • 第 98–100 行:成功:计数器清零,令牌存入 Cookie,重定向到该角色的主页;
  • 第 105–109 行:注销,使用 POST(参见示例 25);
  • 第 115 行:客户端的 IP 地址,由网络连接提供([RemoteIpAddress],它可能为 [null],因此使用 [?.] 和 [??])。该方法是公共静态的:[RegistrationController] 和 [PatientAreaController] 也将它用于限制器。在中间服务器(例如 [nginx] 这样的反向代理)之后,该地址会是代理的地址:注释中指明了这种情况下需要启用的中间件;
  • 第 118–125 行:登录页面,始终带有 新的 验证码:每张图像只使用一次。它的模型 [LoginModel] (文件夹 [Models])包含页面标题(翻译键)、输入的用户名(绝不包含密码)、验证码,以及任何错误消息及其翻译键和参数。[error] 和 [errorParams] 是 可选参数:当调用未提供它们时,默认为 [null] 。

11.14. Web 层:共享服务

在讲解控制器和视图之前,先看看它们的共同点:翻译、视图的父类、闪现消息、异常过滤器、医生和客户列表的缓存、为重新显示而准备的表单,以及一些实用函数。所有这些文件都在 [Web] 文件夹中。它汇集了示例 16 至 24 中的大部分技术。

11.14.1. Web/Translator.cs

// =========================================================================
// Web/Translator.cs
// -------------------------------------------------------------------------
// 界面的法语 / 英语翻译。
//
// 字典与 NestJS 项目的文件相同
// (i18n/fr.json、i18n/en.json),仅在启动时读取一次。Razor
// 视图用 @T("KEY") 翻译一个键(参见 Web/ViewPage.cs)。
//
// ASP.NET Core 也提供自己的系统(IStringLocalizer 和
// .resx 文件);保留 JSON 文件则可以与应用的
// 其他版本共享字典。
//
// 当前语言:由 ASP.NET Core 的本地化中间件
// (UseRequestLocalization,参见 Program.cs)在每个请求上根据
// Cookie 确定,并存入 CultureInfo.CurrentUICulture。
// =========================================================================

using System.Globalization;
using System.Text.Json;
using System.Text.RegularExpressions;

namespace RdvMedecins.Web;

public partial class Translator
{
    public static readonly string[] Languages = ["fr", "en"];
    public const string DefaultLanguage = "en";

    // 语言 -> (完整键 "LOGIN.TITLE" -> 文本)
    private readonly Dictionary<string, Dictionary<string, string>> dictionaries = [];

    public Translator(IWebHostEnvironment environment)
    {
        foreach (var language in Languages)
        {
            var path = Path.Combine(environment.ContentRootPath, "i18n", $"{language}.json");
            using var document = JsonDocument.Parse(File.ReadAllText(path));
            var dictionary = new Dictionary<string, string>();
            Flatten(document.RootElement, "", dictionary);
            dictionaries[language] = dictionary;
        }
    }

    // 当前请求的语言:"fr" 或 "en"
    public static string CurrentLanguage()
    {
        var language = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;
        return Languages.Contains(language) ? language : DefaultLanguage;
    }

    // -----------------------------------------------------------------------
    // Translate("DOCTORS.ADDED", { ["name"] = "Marie PELISSIER" })
    //   -> 在当前语言的字典中查找 "DOCTORS.ADDED",
    //      并将 {name} 替换为其值。请求的语言中缺失的键
    //      会在默认语言中查找;若处处缺失,
    //      则显示键本身(这样遗漏会被立即发现)。
    // -----------------------------------------------------------------------
    public string Translate(string? key, IReadOnlyDictionary<string, string>? messageParams = null)
    {
        if (string.IsNullOrEmpty(key))
        {
            return "";
        }
        var text = dictionaries[CurrentLanguage()].GetValueOrDefault(key)
                    ?? dictionaries[DefaultLanguage].GetValueOrDefault(key)
                    ?? key;
        if (messageParams is null || messageParams.Count == 0)
        {
            return text;
        }
        return Parameter().Replace(text, m => messageParams.TryGetValue(m.Groups[1].Value, out var value) ? value : m.Value);
    }

    // { "LOGIN": { "TITLE": "Login" } } -> { "LOGIN.TITLE": "Login" }
    private static void Flatten(JsonElement node, string prefix, Dictionary<string, string> result)
    {
        foreach (var property in node.EnumerateObject())
        {
            var key = prefix == "" ? property.Name : $"{prefix}.{property.Name}";
            if (property.Value.ValueKind == JsonValueKind.Object)
            {
                Flatten(property.Value, key, result);
            }
            else
            {
                result[key] = property.Value.GetString() ?? "";
            }
        }
    }

    // {name} 正则表达式,由 C# 编译器一次性编译好
    // ([GeneratedRegex] "源生成器")
    [GeneratedRegex(@"\{(\w+)\}")]
    private static partial Regex Parameter();
}

这就是示例 22 中的翻译服务,在 [Program.cs] 中注册为单例:字典 [i18n/fr.json] 和 [i18n/en.json] 与 [NestJS] 版本中的文件相同,只在启动时读取一次。只有一处不同:

  • 第 65–67 行:法语字典中缺失的键会到英语字典([DefaultLanguage])中查找;如果各处都缺失,则显示键本身。两个 [??] 运算符串联在一起:取第一个不为 [null] 的值。

11.14.2. Web/ViewPage.cs

// =========================================================================
// Web/ViewPage.cs
// -------------------------------------------------------------------------
// 应用中所有 Razor 视图的父类(参见
// Views/_ViewImports.cshtml:@inherits ViewPage<TModel>)。
//
// .cshtml 视图会被编译为一个 C# 类,是 RazorPage<TModel> 的子类。
// 通过插入我们自己的类,我们为所有视图提供它们
// 所需的一切,无论是哪个页面:
//   - @T("KEY") :键的翻译(相当于
//                          Handlebars 辅助函数 {{t 'KEY'}});
//   - Language :"fr" 或 "en";
//   - CurrentUser :已连接的用户,用于导航栏;
//   - FlashMessage :请求的闪现消息;
//   - CurrentPath :请求的 URL(导航栏的活动菜单)。
// 在 NestJS 中,这些信息通过 res.locals 传递。
// =========================================================================

using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Razor.Internal;
using RdvMedecins.Auth;

namespace RdvMedecins.Web;

public abstract class ViewPage<TModel> : RazorPage<TModel>
{
    // [RazorInject]:该属性通过依赖注入填充,
    // 就像视图中的 @inject 指令所做的那样
    [RazorInject]
    public Translator Translator { get; set; } = null!;

    // -----------------------------------------------------------------------
    // @T("BOOKING_DIALOG.SLOT", ("time", "8:00 - 8:20"))
    // 参数是"元组"(名称,值):一种紧凑的语法,
    // 用来书写值对。
    // 返回的文本随后会被 Razor 转义(< 变为 &lt;):
    // 因此用户输入的名称无法向页面注入 HTML。
    // -----------------------------------------------------------------------
    public string T(string? key, params (string Name, object? Value)[] messageParams) =>
        Translator.Translate(key, messageParams.ToDictionary(p => p.Name, p => p.Value?.ToString() ?? ""));

    // 同上,用于闪现消息或 BusinessException 的参数
    public string T(string? key, IReadOnlyDictionary<string, string>? messageParams) => Translator.Translate(key, messageParams);

    public string Language => Translator.CurrentLanguage();

    public ViewUser? CurrentUser => ViewUser.Of(Context.User.CurrentUser());

    public FlashMessage? FlashMessage => Flash.Read(Context);

    public string CurrentPath => Context.Request.Path.Value ?? "/";

    // 如果当前页面位于此路径之下则为 "active"(导航栏的菜单)
    public string Active(string prefix) => CurrentPath.StartsWith(prefix, StringComparison.Ordinal) ? "active" : "";
}

// -------------------------------------------------------------------------
// 视图所看到的已连接用户
// -------------------------------------------------------------------------
public record ViewUser(string Login, string Name, string Role, bool IsAdmin, bool IsPatient)
{
    public static ViewUser? Of(ConnectedUser? u) =>
        u is null
            ? null
            : new ViewUser(
                u.Login,
                u.Name,
                u.Role.ToString(),
                IsAdmin: u.Role == Entities.Role.ADMIN, // ADMIN:医生 / 患者菜单
                IsPatient: u.Role == Entities.Role.USER); // USER:我的空间菜单
}

我们来分析这段代码:

  • 第 25 行:所有视图的父类,由 [@inherits] 指令指定,位于 [Views/_ViewImports.cshtml] 中,与示例 22 相同。它的作用与 [res.locals] 在 [NestJS] 版本中相同:为每个视图提供所有页面都需要的内容;
  • 第 29–30 行:翻译服务,被注入到属性中(参见示例 22);
  • 第 39–40 行:示例 22 中的 [T] 方法:[@T("KEY", ("name", value))]。渲染的文本由 [Razor] 转义:用户输入的名称无法向页面注入 HTML;
  • 第 43 行:[T] 的第二个版本,它直接接受字典:闪现消息或 [BusinessException] 的参数正是以这种形式传递的。两个名称相同、参数不同的方法称为 重载方法:编译器根据实参选择正确的那一个;
  • 第 45 行:当前语言([fr] 或 [en]),用于页面的 [lang] 属性以及 FR / EN;
  • 第 47 行:已登录的用户,用于导航栏,如果没有则为 [null] 。[Context.User] 是请求的用户,由身份验证中间件根据 JWT 令牌重建(参见第 8 章);方法 [CurrentUser()] (文件 [Auth/ConnectedUser.cs])从中提取账户。在 [NestJS] 版本中,需要一个拦截器在守卫之后将 [req.user] 复制到 [res.locals] 中;而在这里,该属性是在视图读取它时才计算的,那时身份验证早已完成;
  • 第 49 行:请求的闪现消息(参见下文的 [Web/Flash.cs]);
  • 第 51–54 行:所请求 URL 的路径,以及一个方法,如果当前页面位于给定路径之下,该方法就返回 [active] :导航栏就是这样高亮当前菜单项的,例如 [@Active("/my-")] (参见示例 16)。[StringComparison.Ordinal] 逐个字符地比较,与语言无关;
  • 第 60–70 行:视图所看到的已登录用户:登录名、姓名、角色,以及两个布尔值 [IsAdmin] 和 [IsPatient],它们使视图无需自行比较角色。静态方法 [Of] 根据已登录的账户创建此对象,或返回 [null];运算符 [? :] 在两者之间进行选择。实参 [IsAdmin:] 和 [IsPatient:] 是 命名的:参数名写在值之前,使调用更易读。

11.14.3. Web/Flash.cs

// =========================================================================
// Web/Flash.cs
// -------------------------------------------------------------------------
// "闪现"消息:一条只显示一次、在下一个页面显示的
// 消息。它是 "Post / Redirect / Get" 模式的自然补充,
// 应用的所有表单都使用该模式:成功的 POST 不会
// 构建页面,而是重定向(302)到一个 GET 页面,如果
// 用户随后刷新该页面(F5),浏览器不会第二次发送
// 表单。然而,
// 消息必须在重定向后保留下来。
//
// 在 NestJS 中,我们自己编写了它(一个短期 Cookie)。
// ASP.NET Core MVC 则内置提供:即 TempData。存入
// TempData 的值会保留(默认存放在加密的 Cookie 中),
// 直到后续请求读取它,然后被清除。
// =========================================================================

using System.Text.Json;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace RdvMedecins.Web;

public enum FlashType
{
    Success, // Bootstrap 的 alert-success 类:位于页面顶部
    Danger, // 错误:位于页面底部(参见 Views/Shared/_Errors.cshtml)
}

// Key:翻译键;Params:其参数({name}、{login}……)
public record FlashMessage(FlashType Type, string Key, Dictionary<string, string>? Params = null);

public static class Flash
{
    private const string Key = "flash";

    // -----------------------------------------------------------------------
    // 放入一条闪现消息,将由下一个页面显示。
    // 我们通过 ITempDataDictionaryFactory(而不是控制器的
    // TempData 属性),以便能从任何地方放入消息:
    // 控制器,也包括在 MVC 之外运行的 JWT 身份验证
    // (会话过期,参见 Auth/JwtAuthentication.cs)。
    // -----------------------------------------------------------------------
    public static void Put(HttpContext http, FlashType type, string key, Dictionary<string, string>? messageParams = null)
    {
        var tempData = TempDataOf(http);
        // TempData 只能保存简单值:我们把
        // 消息存为 JSON 文本
        tempData[Key] = JsonSerializer.Serialize(new FlashMessage(type, key, messageParams));
        // Save():立即写入 Cookie(在 MVC 之外没有人
        // 会替我们做)
        tempData.Save();
    }

    // -----------------------------------------------------------------------
    // 读取(因而清除)请求的闪现消息。页面可能
    // 多次请求它(成功消息显示在顶部,错误消息
    // 显示在底部):我们把它保存在 HttpContext.Items 中,这是一个
    // 在请求期间存活的字典。
    // -----------------------------------------------------------------------
    public static FlashMessage? Read(HttpContext http)
    {
        if (http.Items.TryGetValue(Key, out var alreadyRead))
        {
            return alreadyRead as FlashMessage;
        }
        FlashMessage? message = null;
        if (TempDataOf(http)[Key] is string json)
        {
            try
            {
                message = JsonSerializer.Deserialize<FlashMessage>(json);
            }
            catch (JsonException)
            {
                // 无法读取的消息:忽略它
            }
        }
        http.Items[Key] = message;
        return message;
    }

    private static ITempDataDictionary TempDataOf(HttpContext http) =>
        http.RequestServices.GetRequiredService<ITempDataDictionaryFactory>().GetTempData(http);
}

下面对这段代码进行说明:

  • 第 23–26 行:两种类型的消息:成功消息,显示在页面顶部(分部视图 [_Flash.cshtml]),以及错误消息,显示在页面底部(分部视图 [_Errors.cshtml]);
  • 第 30 行:闪现消息由翻译键及其参数组成,而不是预先翻译好的文本;它将在下一个页面中按该页面的语言进行翻译;
  • 第 32 行:只包含函数的静态类(参见 [Web/Utils.cs])。[TempData] (参见示例 20)完成了大部分工作:它将值存储在加密的 Cookie 中,直到下一个请求,并在读取后将其删除。在 [NestJS] 版本中,这个短期 Cookie 是手工编程实现的;
  • 第 43–51 行:设置消息。[TempData] 只能存储简单的值(文本、数字):消息被存储为文本 JSON([JsonSerializer.Serialize])。该方法接收 [HttpContext] ,而不是控制器的 [TempData] 属性:因此它可以在 MVC 之外被调用,例如在会话过期时由 JWT 身份验证调用(参见 [Auth/JwtAuthentication.cs])。在 MVC 之外,没有人会在请求结束时保存 [TempData] :[Save()] 会立即写入 Cookie;
  • 第 60–79 行:读取请求的消息。读取 [TempData] 会将其标记为已消耗;然而页面要读取它两次(顶部用于成功消息,底部用于错误消息)。因此第一次调用将结果存储在 [HttpContext.Items] 这个请求范围的字典中(参见第 6 章),第二次调用从那里取回它(第 62 行);
  • 第 71–73 行:[Deserialize] 从 JSON 重建 [FlashMessage] 对象。无法读取的文本不应导致页面失败:异常会被捕获,消息被忽略;
  • 第 82–83 行:请求的 [TempData] ,从 [ITempDataDictionaryFactory] 服务获得。[RequestServices] 使静态类能够访问依赖注入,因为静态类不能通过构造函数接收服务。

11.14.4. Web/HtmlExceptionFilter.cs

// =========================================================================
// Web/HtmlExceptionFilter.cs
// -------------------------------------------------------------------------
// 错误如何变成 HTML 页面。ASP.NET Core 的三种机制
// 分担这项工作(参见 Program.cs):
//
//   1. 此 MVC 异常过滤器:InvalidSessionException(登录后
//      账户已被删除)-> 返回登录页面;
//   2. UseStatusCodePagesWithReExecute("/error/{0}"):任何没有内容的
//      400、403 或 404 响应(return BadRequest()、角色不足、未知
//      页面……)都会被相应的错误页面替换;
//   3. UseExceptionHandler("/error/500"):任何其他异常(真正的
//      故障)会写入服务器日志,用户
//      看到 500 错误页面,绝不会看到调用栈。
//
// 在 NestJS 中,由单个过滤器(HtmlExceptionFilter)完成所有这些。
// =========================================================================

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using RdvMedecins.Auth;

namespace RdvMedecins.Web;

public class HtmlExceptionFilter : IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        if (context.Exception is InvalidSessionException)
        {
            AuthService.ClearToken(context.HttpContext.Response);
            Flash.Put(context.HttpContext, FlashType.Danger, "ERRORS.SESSION_EXPIRED");
            context.Result = new RedirectResult("/login");
            context.ExceptionHandled = true;
        }
        // 其他异常不在此处理:它们会向上传递
        // 到 UseExceptionHandler(500 页面)
    }
}

下面对这段代码进行说明:

  • 第 25 行:一个异常过滤器,与示例 24 中相同,作为全局过滤器添加到 [Program.cs] 中。在 [NestJS] 版本中,单个过滤器就将所有错误转换为 HTML 页面。在这里,工作由框架的两个中间件组件分担,它们在 [Program.cs] 中配置:[UseStatusCodePagesWithReExecute] 将没有内容的 400、403 和 404 响应替换为相应的错误页面(参见示例 24),而 [UseExceptionHandler("/error/500")] 拦截所有其他异常:错误连同其调用堆栈会记录在服务器日志中,但用户只会看到 500 错误页面,因为这些细节可能会帮助攻击者;
  • 第 29–34 行:该过滤器只处理一种情形:已登录用户的账户在其登录后被删除,而其令牌仍然有效(参见下文的 [Web/Utils.cs])。此时会清除令牌 Cookie,显示“会话已过期”的闪存消息,并将用户重定向到登录页面。其他异常不会被标记为已处理:它们会继续传递给 [UseExceptionHandler]。

11.14.5. Web/ApplicationModel.cs

// =========================================================================
// Web/ApplicationModel.cs
// -------------------------------------------------------------------------
// JSON 服务器中已有的缓存 / 外观(相当于 Spring 项目的
// [ApplicationModel] 类):医生和客户的列表在启动时读取一次,
// 之后从内存中提供。
//
// 这些列表可能变化(ADMIN 添加、编辑、删除
// 医生和客户):因此每次写入都经过此外观,
// 它会在写入后立即重新加载相关的列表。这就是
// 业务层只有一个入口的全部意义:规则"写入 =>
// 重新加载缓存"只在此处编写。
//
// 与 NestJS 的重要区别:对象的生命周期。
//   - 在 NestJS 中,所有服务都是单例。
//   - 这里,DbContext(因此也包括仓库和业务层)只在
//     一次 HTTP 请求期间存活("scoped" 生命周期,参见 Program.cs)。
//   - 但缓存必须在请求之间保留。
// 因此我们把这两个角色分开:
//   - ListCache(单例):两个列表,仅此而已;
//   - ApplicationModel(scoped):外观,它使用
//     当前请求的业务层并更新缓存。
// =========================================================================

using RdvMedecins.Domain;
using RdvMedecins.Entities;
using RdvMedecins.Business;

namespace RdvMedecins.Web;

// -------------------------------------------------------------------------
// 缓存本身,由所有请求共享(单例)。
//
// ASP.NET Core 在多个线程上并行处理请求
// (而 Node 只有一个线程)。因此我们从不就地修改列表:而是
// 用一个新列表整体替换它。交换引用是原子的;
// "volatile" 保证所有线程立即看到新列表。
// -------------------------------------------------------------------------
public class ListCache
{
    private volatile IReadOnlyList<Doctor> doctors = [];
    private volatile IReadOnlyList<Client> clients = [];

    public IReadOnlyList<Doctor> Doctors
    {
        get => doctors;
        set => doctors = value;
    }

    public IReadOnlyList<Client> Clients
    {
        get => clients;
        set => clients = value;
    }
}

// -------------------------------------------------------------------------
// 外观(scoped):与业务层(IBusiness)相同的契约。
// -------------------------------------------------------------------------
public class ApplicationModel(IBusiness business, ListCache cache) : IBusiness
{
    // 两个列表的初始加载,在启动时调用一次
    // (参见 Program.cs)。如果数据库无法访问,异常会以明确的消息
    // 终止服务器,这比"空"启动更清晰。
    public async Task LoadAsync()
    {
        await ReloadDoctorsAsync();
        await ReloadClientsAsync();
    }

    private async Task ReloadDoctorsAsync() => cache.Doctors = await business.GetAllDoctorsAsync();

    private async Task ReloadClientsAsync() => cache.Clients = await business.GetAllClientsAsync();

    // 从缓存读取

    public Task<List<Doctor>> GetAllDoctorsAsync() => Task.FromResult(cache.Doctors.ToList());

    public Task<List<Client>> GetAllClientsAsync() => Task.FromResult(cache.Clients.ToList());

    // 用户账户为 [userId] 的医生,用于为已登录的医生
    // 预选其自己的日程
    public Doctor? GetDoctorByUserId(int userId) => cache.Doctors.FirstOrDefault(d => d.UserId == userId);

    // 简单委托

    public Task<List<Slot>> GetAllSlotsAsync(int doctorId) => business.GetAllSlotsAsync(doctorId);

    public Task<List<Appointment>> GetDoctorDayAppointmentsAsync(int doctorId, DateOnly day) => business.GetDoctorDayAppointmentsAsync(doctorId, day);

    public Task<Client?> GetClientByIdAsync(int id) => business.GetClientByIdAsync(id);

    public Task<Doctor?> GetDoctorByIdAsync(int id) => business.GetDoctorByIdAsync(id);

    public Task<Appointment?> GetAppointmentByIdAsync(int id) => business.GetAppointmentByIdAsync(id);

    public Task<Slot?> GetSlotByIdAsync(int id) => business.GetSlotByIdAsync(id);

    public Task<DoctorDaySchedule?> GetDoctorDayScheduleAsync(int doctorId, DateOnly day) =>
        business.GetDoctorDayScheduleAsync(doctorId, day);

    // 这里不使用缓存:重要的是最新的数据(刚刚
    // 编辑或删除了自己账户的患者)
    public Task<Client?> GetClientByUserIdAsync(int userId) => business.GetClientByUserIdAsync(userId);

    public Task<List<Appointment>> GetClientUpcomingAppointmentsAsync(int clientId) => business.GetClientUpcomingAppointmentsAsync(clientId);

    public Task<Appointment> AddAppointmentAsync(DateOnly day, Slot slot, Client client) => business.AddAppointmentAsync(day, slot, client);

    public Task DeleteAppointmentAsync(Appointment appointment) => business.DeleteAppointmentAsync(appointment);

    // 写入 => 重新加载

    public async Task<Doctor> AddDoctorAsync(PersonData data)
    {
        var doctor = await business.AddDoctorAsync(data);
        await ReloadDoctorsAsync();
        return doctor;
    }

    public async Task<Doctor> EditDoctorAsync(int id, PersonData data)
    {
        var doctor = await business.EditDoctorAsync(id, data);
        await ReloadDoctorsAsync();
        return doctor;
    }

    public async Task DeleteDoctorAsync(int id)
    {
        await business.DeleteDoctorAsync(id);
        await ReloadDoctorsAsync();
    }

    public async Task<Client> AddClientAsync(PersonData data)
    {
        var client = await business.AddClientAsync(data);
        await ReloadClientsAsync();
        return client;
    }

    public async Task<Client> EditClientAsync(int id, PersonData data)
    {
        var client = await business.EditClientAsync(id, data);
        await ReloadClientsAsync();
        return client;
    }

    public async Task DeleteClientAsync(int id)
    {
        await business.DeleteClientAsync(id);
        await ReloadClientsAsync();
    }
}

医生和客户的列表几乎出现在每个页面中(日历下拉列表、管理页面)。我们不在每次请求时都从数据库中检索它们,而是将其保存在内存中:这是应用程序范围的数据(参见第 6 章)。[NestJS] 版本把这个角色交给了一个单独的服务,它与所有 [NestJS] 服务一样是单例。在 [ASP.NET Core] 中这是行不通的:业务层使用 [DbContext],它只在一次请求期间存在([Scoped] 服务;参见第 9 章),而单例不能接收 [Scoped] 服务。因此我们把这两个角色拆分到两个类中。

我们来逐段说明这段代码:

  • 第 39 行:缓存本身,注册为单例([AddSingleton<ListCache>()] 位于 [Program.cs] 中)。它只包含两个列表;
  • 第 41–42 行:[ASP.NET Core] 通过多个线程([threads])并行处理请求,而 [Node.js] 只有一个线程。因此,当另一个请求正在遍历共享列表时,绝不能修改它。我们选择的规则很简单:从不修改列表,而是用新列表替换它。替换引用只需一次操作即可完成,关键字 [volatile] 确保所有线程都能立即看到新列表。[IReadOnlyList] 只允许读取:编译器禁止添加或删除元素;
  • 第 60 行:外观,注册为 [Scoped] 服务([AddScoped<ApplicationModel>()])。它接收当前请求的业务层和共享缓存。它实现了与业务层相同的 [IBusiness] 接口:对控制器而言,它就是业务层,并且是控制器收到的唯一一个;
  • 第 65–68 行:两个列表的初始加载。它由 [Program.cs] 在服务器启动前调用一次。[Scoped] 服务只存在于某个作用域内:[Program.cs] 为此创建了一个作用域([CreateScope])。如果数据库无法访问,异常会带着明确的消息终止应用程序,这比用空列表启动服务器要好;
  • 第 71–73 行:重新加载列表:从数据库读取整个列表并替换缓存中的列表;
  • 第 77–79 行:列表从内存中提供。[IBusiness] 接口声明了一个异步方法:[Task.FromResult] 创建一个已完成的任务,并携带结果。[ToList()] 返回列表的副本:调用方可以修改它而不影响缓存;
  • 第 83 行:与某个账户关联的医生,从缓存中获取:已登录的医生可以立即看到自己的日程;
  • 第 87–110 行:其他请求原样转发给业务层;
  • 第 104 行:与某个账户关联的客户有意不从缓存中查找;刚修改或删除了自己账户的患者,必须按其在数据库中的实际状态显示;
  • 第 114–151 行:任何涉及医生或客户的写操作之后,都会刷新相应的列表。由于该服务是控制器访问业务层的唯一入口,“写入 = 刷新缓存”这条规则只在这里实现,缓存就不会变得陈旧。如果业务层拒绝该操作([BusinessException]),异常会在缓存重新加载之前终止该方法,因为此时已无需这一步。

11.14.6. Web/Validation.cs

// =========================================================================
// Web/Validation.cs
// -------------------------------------------------------------------------
// 重新显示被拒绝的表单所需的内容:逐字段的输入错误,
// 以及要标红的字段。
// =========================================================================

using Microsoft.AspNetCore.Mvc.ModelBinding;
using RdvMedecins.Models;

namespace RdvMedecins.Web;

public static class Validation
{
    // -----------------------------------------------------------------------
    // ModelState(由 MVC 在绑定表单时填充)->
    // 字段 -> 消息键的字典,每个字段只保留
    // 第一条消息:{ "LastName": "ERRORS.LASTNAME_REQUIRED", ... }
    // -----------------------------------------------------------------------
    public static Dictionary<string, string> ErrorsOf(ModelStateDictionary modelState)
    {
        var errors = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        foreach (var (field, entry) in modelState)
        {
            if (entry.Errors.Count > 0)
            {
                var message = entry.Errors[0].ErrorMessage;
                errors[field] = string.IsNullOrEmpty(message) ? "ERRORS.INVALID_FORM" : message;
            }
        }
        return errors;
    }

    // -----------------------------------------------------------------------
    // 每个"输入"业务错误(重复)所涉及的表单字段:
    // 它们会被标红,消息位于页面底部
    // -----------------------------------------------------------------------
    public static readonly Dictionary<string, string[]> BusinessErrorFields = new()
    {
        ["ERRORS.LOGIN_TAKEN"] = ["login"],
        ["ERRORS.DOCTOR_ALREADY_EXISTS"] = ["firstName", "lastName"],
        ["ERRORS.PATIENT_ALREADY_EXISTS"] = ["firstName", "lastName"],
    };

    // -----------------------------------------------------------------------
    // 为表单模型的(重新)显示做准备:
    //   errors :每个被验证拒绝的字段下方的消息
    //   error :页面的错误消息,显示在页面底部;
    //                  如果存在字段错误,默认为 "The form contains errors."
    //                  (见上)
    //   otherFields :要标红但没有自己消息的字段
    // -----------------------------------------------------------------------
    public static T Prepare<T>(
        T model,
        Dictionary<string, string>? errors = null,
        string? error = null,
        IEnumerable<string>? otherFields = null,
        IReadOnlyDictionary<string, string>? errorParams = null) where T : FormView
    {
        model.Errors = errors ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        model.InvalidFields = new HashSet<string>(model.Errors.Keys.Concat(otherFields ?? []), StringComparer.OrdinalIgnoreCase);
        model.Error = error ?? (model.Errors.Count > 0 ? "ERRORS.INVALID_FORM" : null);
        model.ErrorParams = errorParams;
        return model;
    }
}

我们来逐段说明这段代码:

  • 第 20–31 行:将 [ModelState] (参见示例 07 和 19)转换为简单的“字段 → 消息键”字典。每个字段只保留第一条消息:字段下方只显示一条消息。该字典忽略大小写(第 22 行):[ModelState] 根据属性([LastName]、[Login])为字段命名,而视图则根据 HTML 字段([lastName]、[login])来请求它们;
  • 第 27–28 行:作为预防措施,没有消息的错误(例如由异常引起的错误)会被赋予通用消息 [ERRORS.INVALID_FORM];
  • 第 38–42 行:业务层的某些错误与特定字段有关:已被占用的用户名,或姓名相同的医生或客户。这些字段将以红色高亮显示,消息显示在页面底部。语法 [["key"] = value] 在字典创建时即完成填充;
  • 第 53–64 行:准备用于显示或重新显示的表单模型:字段下方的消息([Errors])、需要用红框标出的字段([InvalidFields]:带有消息的字段,加上 [otherFields] 字段,第 61 行)、页面底部的消息及其参数。在没有明确消息时,字段错误会产生“表单包含错误”这条消息(第 62 行)。该方法是泛型的:约束 [where T : FormView] (第 58 行)接受任何派生自 [FormView] 的模型(参见 [Models/ViewModels.cs]),并以其确切类型返回该模型,可直接传给 [View]。这些参数都有默认值([= null]):调用方只需提供它需要的参数。

11.14.7. Web/Utils.cs

// =========================================================================
// Web/Utils.cs
// -------------------------------------------------------------------------
// Web 层的小型工具函数:
//   - Labels :"Mme Alice DURAND";
//   - WebDates :日期 "yyyy-MM-dd",时间 "8:05",日 "Wednesday 23 September 2026";
//   - Input :读取浏览器发送的正整数;
//   - Patient :已连接用户的患者(Client 实体)。
//
// "静态"类:它们只包含函数,我们从不创建
// 这些类的对象。
// =========================================================================

using System.Globalization;
using System.Security.Claims;
using RdvMedecins.Auth;
using RdvMedecins.Entities;

namespace RdvMedecins.Web;

public static class Labels
{
    // "Mme Alice DURAND"
    public static string Label(Person p) => $"{p.Title} {p.FirstName} {p.LastName}";
}

public static class WebDates
{
    // URL 中以及 <input type="date"> 字段中的日期格式
    public const string IsoFormat = "yyyy-MM-dd";

    // 如果 [day] 是 yyyy-MM-dd 格式的真实存在的日期则为 true
    // ("2026-02-30" 会被拒绝)
    public static bool IsValidDate(string? text, out DateOnly day) =>
        DateOnly.TryParseExact(text, IsoFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out day);

    public static string Iso(DateOnly day) => day.ToString(IsoFormat, CultureInfo.InvariantCulture);

    // "8:05" 而不是 "8:5"
    public static string FormatTime(int h, int m) => $"{h}:{m:00}";

    public static string Time(Slot s) => $"{FormatTime(s.StartHour, s.StartMinute)} - {FormatTime(s.EndHour, s.EndMinute)}";

    // "mercredi 23 septembre 2026" / "Wednesday 23 September 2026",取决于
    // 请求的语言(CultureInfo.CurrentCulture,由
    // 本地化中间件设置,参见 Program.cs)
    public static string FormatDay(DateOnly day) =>
        day.ToString("dddd d MMMM yyyy", CultureInfo.CurrentCulture);
}

public static class Input
{
    // "3" -> 3 ;"", "abc", "-2", null -> null
    public static int? PositiveInteger(string? value) =>
        int.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var n) && n > 0 ? n : null;
}

public static class Patient
{
    // -----------------------------------------------------------------------
    // 与已连接用户对应的患者(Client 实体)。
    //
    // JWT 令牌只包含账户的 id(users.id)。对于
    // USER 角色,我们借助 clients.user 列找到对应的客户。
    //
    // 如果没有找到,说明账户在登录之后已被删除,
    // 而其令牌仍然有效:我们将其视为
    // 会话过期(参见 InvalidSessionException)。
    // -----------------------------------------------------------------------
    public static async Task<Client> ConnectedPatientAsync(ApplicationModel application, ClaimsPrincipal user)
    {
        var currentUser = user.CurrentUser() ?? throw new InvalidSessionException();
        return await application.GetClientByUserIdAsync(currentUser.UserId) ?? throw new InvalidSessionException();
    }
}

我们来逐段分析这段代码:

  • 第 24 行:医生或客户的姓名:“Mme Alice DURAND”。该参数的类型为 [Person],即实体 [Doctor] 和 [Client] 的父类:两者使用同一个函数;
  • 第 30 行:URL 中以及 [<input type="date">] 字段中使用的日期格式;
  • 第 34–35 行:如果文本是 [yyyy-MM-dd] 格式且确实存在的日期,则返回 true;[2026-02-30] 会被拒绝(参见示例 12)。结果通过参数 [out day] 返回。[CultureInfo.InvariantCulture] 使解析与请求的语言无关;
  • 第 37 行:反向操作:把日期转换为文本 [yyyy-MM-dd];
  • 第 40–42 行:格式为 [8:05] 的时间([00] 格式要求分钟为两位数字),以及时间段的时间:[8:00 - 8:20];
  • 第 47–48 行:根据请求的区域设置(由本地化中间件确定,参见示例 22)完整写出的日期:“mercredi 23 septembre 2026”或“Wednesday 23 September 2026”;
  • 第 54–55 行:浏览器发送的标识符(在 URL 或表单字段中):严格正整数,或 [null]。[NumberStyles.None] 只接受数字:不接受符号、空格或千位分隔符。控制器只需测试 [null] 即可;
  • 第 70–73 行:与已登录用户关联的患者(实体 [Client])。JWT 令牌只包含账户 ID;我们据此查找与该账户关联的客户。如果该客户已不存在,则说明账户在用户登录后被删除:[InvalidSessionException] 将由上文所述的 [HtmlExceptionFilter] 过滤器处理,并重定向到登录页面。[?? throw] 在左侧的值为 [null] 时抛出异常(参见第 9 章)。

11.15. 表单模型与视图模型

有两类类在浏览器、控制器和视图之间传输数据:表单,由模型绑定根据浏览器发送的内容填充;以及视图模型,由控制器为视图准备。前者对应 [NestJS] 版本中的 DTO 对象,后者对应传给 [res.render] 的对象。

11.15.1. Models/Forms.cs

// =========================================================================
// Models/Forms.cs
// -------------------------------------------------------------------------
// "人员"表单的字段及其约束。三个
// 表单共享相同的身份字段(称谓、名、姓):
//
//   PersonFields 称谓、名、姓
//    ├─ PersonForm + 可选的登录名 / 密码、版本
//    │ (ADMIN 添加或编辑医生 / 客户)
//    ├─ RegistrationForm + 必填的登录名 / 密码 / 确认密码
//    │ (患者创建其账户)
//    └─ MyAccountForm + 登录名、可选的新密码、
//                                   必填的当前密码、版本
//                                   (患者编辑其账户)
//
// 模型绑定:当控制器操作接收到
// 这些类之一的参数时,ASP.NET Core MVC 会创建对象,
// 并用同名的表单字段填充每个属性(不区分
// 大小写:"lastName" 字段填充 LastName 属性)。
//
// 验证:紧接着,MVC 检查 [Required]、
// [MaxLength]……特性(标准命名空间 System.ComponentModel.DataAnnotations,
// 相当于 class-validator),并把错误存入 ModelState。
// 控制器只需测试 ModelState.IsValid。
//
// 错误消息是翻译键(参见 i18n/*.json)。
//
// 输入清理(相当于 class-transformer 的 @Transform):
//   - MVC 已经将空字段转为 null;
//   - 下面的 setter 会去掉多余的空格,并把
//     登录名转为小写。但密码不做"清理"(空格
//     可能是密码的一部分)。
// 所有属性都是"可空的"(string?):浏览器发送的内容中
// 字段总可能缺失;要求它存在的是 [Required]。
// =========================================================================

using System.ComponentModel.DataAnnotations;

namespace RdvMedecins.Models;

public static class InputRules
{
    public static readonly string[] Titles = ["Mr", "Mme", "Melle"];

    // 登录名:小写字母、数字、点、连字符、下划线,最多 30 个字符
    public const string LoginFormat = "^[a-z0-9._-]{1,30}$";

    // 患者所选密码的最小长度
    public const int PasswordMin = 6;

    // " dupont " -> "dupont" ;" " -> null
    public static string? Clean(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}

// -------------------------------------------------------------------------
// 一个"自制"的验证特性:值必须属于某个列表。
// 只需继承 ValidationAttribute 并编写 IsValid 即可。
// -------------------------------------------------------------------------
public class OneOfAttribute(params string[] values) : ValidationAttribute
{
    // 这里接受 null:要求其存在是 [Required] 的职责
    public override bool IsValid(object? value) => value is null || values.Contains(value as string);
}

// 公共基类
public class PersonFields
{
    [Required(ErrorMessage = "ERRORS.INVALID_TITLE")]
    [OneOf("Mr", "Mme", "Melle", ErrorMessage = "ERRORS.INVALID_TITLE")]
    public string? Title { get; set; }

    // 最大长度 = SQL 列的长度(VARCHAR(20))
    private string? firstName;

    [Required(ErrorMessage = "ERRORS.FIRSTNAME_REQUIRED")]
    [MaxLength(20, ErrorMessage = "ERRORS.FIRSTNAME_TOO_LONG")]
    public string? FirstName
    {
        get => firstName;
        set => firstName = InputRules.Clean(value);
    }

    private string? lastName;

    [Required(ErrorMessage = "ERRORS.LASTNAME_REQUIRED")]
    [MaxLength(20, ErrorMessage = "ERRORS.LASTNAME_TOO_LONG")]
    public string? LastName
    {
        get => lastName;
        set => lastName = InputRules.Clean(value);
    }
}

// ADMIN
public class PersonForm : PersonFields
{
    private string? login;

    // 可选(参见 PersonData、Business/IBusiness.cs)
    [RegularExpression(InputRules.LoginFormat, ErrorMessage = "ERRORS.INVALID_LOGIN")]
    public string? Login
    {
        get => login;
        set => login = InputRules.Clean(value)?.ToLowerInvariant();
    }

    // 可选;最多 72 个字符(超过后,bcrypt 会忽略其余部分)
    [MaxLength(72, ErrorMessage = "ERRORS.PASSWORD_TOO_LONG")]
    public string? Password { get; set; }

    // 编辑表单的隐藏字段(乐观锁)。
    // int?:缺失或为空的字段得到 null;不是
    // 数字的文本会产生绑定错误(参见 Program.cs、ModelBindingMessageProvider)
    public int? Version { get; set; }
}

// 患者注册
public class RegistrationForm : PersonFields
{
    private string? login;

    [Required(ErrorMessage = "ERRORS.LOGIN_REQUIRED")]
    [RegularExpression(InputRules.LoginFormat, ErrorMessage = "ERRORS.INVALID_LOGIN")]
    public string? Login
    {
        get => login;
        set => login = InputRules.Clean(value)?.ToLowerInvariant();
    }

    [Required(ErrorMessage = "ERRORS.PASSWORD_REQUIRED")]
    [MinLength(InputRules.PasswordMin, ErrorMessage = "ERRORS.PASSWORD_TOO_SHORT")]
    [MaxLength(72, ErrorMessage = "ERRORS.PASSWORD_TOO_LONG")]
    public string? Password { get; set; }

    [Required(ErrorMessage = "ERRORS.CONFIRMATION_REQUIRED")]
    public string? Confirmation { get; set; }
}

// "管理我的账户"
public class MyAccountForm : PersonFields
{
    private string? login;

    [Required(ErrorMessage = "ERRORS.LOGIN_REQUIRED")]
    [RegularExpression(InputRules.LoginFormat, ErrorMessage = "ERRORS.INVALID_LOGIN")]
    public string? Login
    {
        get => login;
        set => login = InputRules.Clean(value)?.ToLowerInvariant();
    }

    // 可选:为空 = 密码不变
    [MinLength(InputRules.PasswordMin, ErrorMessage = "ERRORS.PASSWORD_TOO_SHORT")]
    [MaxLength(72, ErrorMessage = "ERRORS.PASSWORD_TOO_LONG")]
    public string? Password { get; set; }

    public string? Confirmation { get; set; }

    // 当前密码,任何账户修改都必须提供
    [Required(ErrorMessage = "ERRORS.CURRENT_PASSWORD_REQUIRED")]
    public string? CurrentPassword { get; set; }

    public int? Version { get; set; }
}

我们来讨论这段代码:

  • 第 43 行:可选的称谓;
  • 第 46 行:用户名的格式,由正则表达式描述:1 到 30 个字符,由小写字母、数字、句点、连字符和下划线组成;
  • 第 49 行:患者所选密码的最小长度。这是一个常量([const]),因此可以用作特性的参数,例如下面的 [[MinLength(InputRules.PasswordMin)]] ;
  • 第 52 行:清理输入:去除首尾空格,仅由空格组成的字段变为 [null],即视为无效;
  • 第 59–62 行:我们编写的验证特性:值必须出现在某个列表中。我们只需从 [ValidationAttribute] 派生并重写 [IsValid] 即可。[null] 会被接受:拒绝缺失字段是 [[Required]] 的职责。我们以 [[OneOf]] 这个名称使用它:按照约定,后缀 [Attribute] 可以省略;
  • 第 66 行:身份字段,三个表单共用。所有属性的类型都是 [string?]:浏览器发送的数据中,字段始终可能缺失,要求其必须存在的是 [[Required]]。错误消息是翻译键(参见示例 22);
  • 第 68–70 行:称谓,必填,并从列表中选择。这些值在 [[OneOf(...)]] 中重复出现:特性的参数必须在编译时已知,而数组 [InputRules.Titles] (一个 [static readonly] 字段,在运行时创建)并非如此;
  • 第 73–80 行和第 83–90 行:名和姓,必填,最多 20 个字符(SQL 列的宽度)。这些属性带有方法体:它们的值存储在私有字段中,并由 [set] 在赋值时进行清理。由于模型绑定在验证之前就给属性赋值,因此验证的是清理后的值。这相当于 [@Transform] 在 [NestJS] 版本中的作用;[ASP.NET Core MVC] 已经会自动把空字段转换为 [null];
  • 第 95 行:ADMIN 表单,用于添加或编辑医生或客户。该类继承了身份字段及其验证特性;
  • 第 97–104 行:登录名,在此处可选,但如果存在则必须符合正确的格式(第 100 行);它会被清理并转换为小写。[?.] 仅当值不是 [null] 时才调用 [ToLowerInvariant];
  • 第 108–109 行:密码,同样可选,最多 72 个字符:对其加密的 [bcrypt] 算法会忽略其后的所有字符。密码不会被清理:空格也算作密码的一部分;
  • 第 114 行:记录的版本,位于更新表单的隐藏字段中(乐观锁;参见示例 28)。字段缺失或为空会得到 [null];不是数字的文本会产生绑定错误,其消息在 [Program.cs] 中配置(参见示例 19);
  • 第 118 行:患者创建账户:用户名、密码(6 到 72 个字符,第 131 行)和确认密码(第 135–136 行)均为必填。验证密码与其确认是否一致涉及两个字段:这由验证器检查([Controllers/RegistrationController.cs]);
  • 第 140 行:患者修改自己的账户。新密码是可选的(第 153 行):如果留空,密码保持不变;因此这里不要求确认密码(第 157 行)。但任何修改都必须提供当前密码(第 160–161 行),记录版本则存储在隐藏字段中(第 163 行)。

11.15.2. Models/ViewModels.cs

// =========================================================================
// Models/ViewModels.cs
// -------------------------------------------------------------------------
// "视图模型":每个控制器传递给
// 其视图(return View("...", model))的内容,是一个类型化的 C# 类。在
// Razor 视图中,@model ScheduleModel 声明模型的类型:编译器
// 随后会检查视图中的每个 @Model.Xxx,拼写错误
// 是编译错误,而不是页面中的一块空白。
//
// 与 Handlebars 一样已遵循的规则:视图中不含逻辑。
// 控制器准备好已经格式化的数据("Mme Marie
// PELISSIER"、"8:00 - 8:20"、Selected = true……),并已根据
// 用户的角色过滤;视图只是把它们放入 HTML。
// =========================================================================

namespace RdvMedecins.Models;

// -------------------------------------------------------------------------
// 所有页面共有的内容,由布局读取
// (Views/Shared/_Layout.cshtml)
// -------------------------------------------------------------------------
public abstract class ViewModel
{
    // 页面标题的翻译键(<title>)
    public string PageTitle { get; set; } = "APP.TITLE";

    // 页面的错误消息,显示在页面底部
    // (参见 Views/Shared/_Errors.cshtml);null = 无错误
    public string? Error { get; set; }

    public IReadOnlyDictionary<string, string>? ErrorParams { get; set; }
}

// 下拉列表的一个选项(医生、患者)
public record OptionView(int Id, string Label, bool Selected);

// 登录
public class LoginModel : ViewModel
{
    public string Login { get; set; } = "";
    public required Auth.Captcha Captcha { get; set; }
}

// 日程
public class ScheduleRowView
{
    public int SlotId { get; init; }
    public string Time { get; init; } = ""; // "8:00 - 8:20"
    public bool Free { get; init; }
    public string? Patient { get; init; } // 已预订时间段显示的名称;null = "Booked"
    public bool Mine { get; init; } // 已连接患者的预约
    public bool Bookable { get; init; } // 是否显示"预订"按钮?
    public string BookUrl { get; init; } = "";
    public int? AppointmentId { get; init; } // 仅在显示"取消"按钮时填充
}

public record ScheduleView(string Doctor, string Day, List<ScheduleRowView> Rows);

public class BookingView
{
    public int SlotId { get; init; }
    public string Time { get; init; } = "";
    // ADMIN / DOCTOR:可供选择的患者列表
    public List<OptionView> Clients { get; init; } = [];
    // USER:患者就是其本人
    public string? Patient { get; init; }
}

public class ScheduleModel : ViewModel
{
    public List<OptionView> Doctors { get; set; } = [];
    public int? DoctorId { get; set; }
    public string Day { get; set; } = ""; // "yyyy-MM-dd"
    public ScheduleView? Schedule { get; set; }
    public BookingView? Booking { get; set; }
    public string BackUrl { get; set; } = "/schedule"; // 显示的日程,不含预订对话框
    // 已有未来预约的患者:解释
    // 为何没有"预订"按钮的消息
    public string? Info { get; set; }
}

// "人员"表单

// 表单字段中显示的值(绝不包含密码)
public class PersonValues
{
    public string Title { get; set; } = "Mr";
    public string FirstName { get; set; } = "";
    public string LastName { get; set; } = "";
    public string Login { get; set; } = "";
    public int? Version { get; set; }
}

// 公共局部视图 _PersonFields.cshtml 使用的内容(称谓、名、姓)
public abstract class FormView : ViewModel
{
    public PersonValues Values { get; set; } = new();

    // 字段 -> 显示在该字段下方的消息键(输入错误)
    public Dictionary<string, string> Errors { get; set; } = new(StringComparer.OrdinalIgnoreCase);

    // 要标红的字段(Bootstrap 的 is-invalid 类):有
    // 消息的字段,以及可能的其他字段(名加姓重复、登录名被占用……)
    public HashSet<string> InvalidFields { get; set; } = new(StringComparer.OrdinalIgnoreCase);

    public string? ErrorOf(string field) => Errors.GetValueOrDefault(field);

    public string InvalidClass(string field) => InvalidFields.Contains(field) ? "is-invalid" : "";

    public IEnumerable<(string Value, bool Selected)> Titles =>
        InputRules.Titles.Select(t => (t, t == Values.Title));
}

public class PersonFormModel : FormView
{
    public bool Creating { get; set; } // true:添加;false:编辑
    public string Action { get; set; } = ""; // POST 的 URL
    public string ListUrl { get; set; } = "";
}

public class RegistrationModel : FormView
{
    public int PasswordMin => InputRules.PasswordMin;
}

public class MyAccountModel : FormView
{
    public int PasswordMin => InputRules.PasswordMin;
}

// 医生 / 客户列表

// 每种人员类型特有的翻译键
public record PersonKeys(
    string Title, // "医生"
    string Add, // "添加医生"
    string Edit, // "编辑医生"
    string Empty, // "没有医生。"
    string ConfirmDelete, // "删除该医生、其时间段及其用户账户?"
    string Added, // "已添加医生 {name}(登录名:{login})。"
    string Edited,
    string Deleted);

public record PersonView(string Title, string FirstName, string LastName, string Login, string EditUrl, string DeleteUrl);

public class PersonListModel : ViewModel
{
    public required PersonKeys Keys { get; set; }
    public string AddUrl { get; set; } = "";
    public List<PersonView> Persons { get; set; } = [];
}

// 患者区域
public record AppointmentView(int Id, string Day, string Time, string Doctor, string ScheduleUrl);

public class AreaModel : ViewModel
{
    public string Patient { get; set; } = "";
    public List<AppointmentView> Appointments { get; set; } = [];
}

// 错误页面
public class ErrorModel : ViewModel
{
    public int Code { get; set; }
    public string Message { get; set; } = "ERRORS.SERVER_ERROR";
}

视图模板遵循我们在 [Handlebars] 中已经应用过的规则:视图中不含逻辑。控制器准备好已格式化的数据(“Mme Marie PELISSIER”、“8:00 – 8:20”),并已根据用户角色过滤;视图只是把这些数据放入 HTML 中。每个视图都声明其模板的类型([@model ScheduleModel],参见示例 13):编译器会检查每一个 [@Model.Xxx],拼写错误会导致编译错误。

我们来逐段说明这段代码:

  • 第 22–31 行:所有页面的共同部分,由 [_Layout.cshtml] 模板读取:页面标题的翻译键(第 25 行),以及显示在底部的页面错误消息及其参数。该类是抽象类:每个页面都有自己的模板,并派生自它;
  • 第 35 行:下拉列表中的一个选项(医生、患者),已标记为选中或未选中(参见示例 18);
  • 第 38–41 行:登录页面:已输入的用户名和要显示的验证码(CAPTCHA)。关键字 [required] 要求创建对象的人必须为该属性赋值;否则会导致编译错误;
  • 第 45–54 行:日历条目,即一个时间段。控制器已经确定了一切:是否显示患者姓名(患者看不到其他人的姓名)、是否显示“预约”按钮,以及是否显示“取消”按钮([AppointmentId] 已设置时)。[init] 属性只能在创建对象时赋值;
  • 第 57 行:医生某一天的日程:医生姓名、完整写出的日期,以及各行;
  • 第 59–66 行:预约窗口:ADMIN 和医生看到的是患者列表,患者则只看到已登录患者的姓名;
  • 第 69–79 行:日历页面:医生列表、所选的医生和日期、日历(在未选择医生时为 [null] )、预约窗口(如果存在)、不带该窗口的日历 URL(第 76 行),以及向患者说明其为何无法预约的消息;
  • 第 85–91 行:“人员”表单字段中显示的值,绝不包括密码:密码不会回传给浏览器;
  • 第 95 行:三个“人员”表单的模板的父类,即 [Validation.Prepare] 所要求的类:字段值、字段下方的消息(第 100 行),以及要以红色高亮的字段(第 104 行)。[HashSet] 是一个集合:每个元素只出现一次,成员测试速度很快;
  • 第 106–108 行:供视图使用的两个方法:字段的消息(或 [null]),以及用红框标出字段的 [Bootstrap] [is-invalid] 类。视图中的用法例如 [@Model.InvalidClass("login")];
  • 第 110–111 行:称谓列表中的选项,并标出被选中的选项(参见示例 18)。每个选项是一个元组 [(Value, Selected)];
  • 第 114–118 行:ADMIN 表单,用于添加和修改(参见示例 28):模式、表单提交 URL,以及返回按钮使用的列表 URL;
  • 第 121–128 行:注册和账户管理表单;它们向视图传递密码的最小长度,该长度用作字段错误消息的 [{min}] 参数,对于注册表单还用于帮助文本;
  • 第 134–142 行:医生和客户管理页面使用相同的视图;只是文本不同。这个 [record] 包含每种人员类型特有的翻译键;
  • 第 144–150 行:医生或客户列表中的一行,带有其“编辑”和“删除”按钮的地址,以及列表页面的模板;
  • 第 154–159 行:患者区域:其姓名和即将到来的预约,每个预约都带有指向当日日历的链接;
  • 第 163–166 行:错误页面:HTTP 代码和消息键,默认是服务器错误的消息键。

11.16. Web 层:控制器

控制器是 Web 层的可见部分:每个控制器接收一组页面的请求,读取其参数,查询业务层(始终通过 [ApplicationModel] 服务),然后选择一个视图并向其传递类型化的模型,或者重定向请求。所有 POST 表单都遵循 Post/Redirect/Get 模式(参见示例 20);所有消息都是翻译键,由视图翻译。登录控制器 [AuthController] 已在身份验证部分讨论过。

11.16.1. Controllers/LanguageController.cs

// =========================================================================
// Controllers/LanguageController.cs
// -------------------------------------------------------------------------
// GET /language/fr、GET /language/en:导航栏上的 FR / EN 两个按钮。
// 非受保护路由:必须允许在
// 登录之前切换语言。
//
// 所选语言存储在 ASP.NET Core 本地化中间件的 Cookie 中
// (CookieRequestCultureProvider,见 Program.cs):之后的每次请求,该中间件都会读回它,
// 并设置请求的语言
// (CultureInfo.CurrentCulture / CurrentUICulture)。然后返回
// 来源页面。
// =========================================================================

using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Mvc;
using RdvMedecins.Web;

namespace RdvMedecins.Controllers;

public class LanguageController : Controller
{
    [HttpGet("language/{language}")]
    public IActionResult Change(string language)
    {
        if (!Translator.Languages.Contains(language))
        {
            return NotFound(); // -> 404 错误页面(见 Program.cs)
        }
        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            // Cookie 值:"c=en|uic=en"(格式所用语言,文本所用语言)
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(language)),
            new CookieOptions { MaxAge = TimeSpan.FromDays(365), SameSite = SameSiteMode.Lax, HttpOnly = true, Path = "/" });
        return Redirect(OriginPage());
    }

    // 上一页,依据浏览器发送的 HTTP "Referer" 头。
    // 我们只保留其路径(/schedule?...):若重定向到请求提供的
    // 完整地址,就可能把
    // 用户带到其他站点(即所谓的"开放重定向"漏洞)。
    private string OriginPage()
    {
        var referer = Request.Headers.Referer.ToString();
        if (!Uri.TryCreate(referer, UriKind.Absolute, out var url))
        {
            return "/";
        }
        return url.AbsolutePath.StartsWith("/language/", StringComparison.Ordinal) ? "/" : url.PathAndQuery;
    }
}

除了一行之外,这就是示例 22 中的控制器:相同的路由 [/language/{language}],相同的本地化中间件 Cookie,并同样通过标头 [Referer] 返回原页面。两点说明:

  • 第 34 行:选项 [Path = "/"] 使该 Cookie 对站点的所有地址都有效,无论是从哪个页面切换的语言;
  • 第 49 行:如果原页面本身就是 [/language/...] 页面,用户会被重定向到站点根目录,而不是返回该页面,否则会导致浏览器陷入循环。

11.16.2. Controllers/ScheduleController.cs

应用程序的主页面,也是功能最丰富的控制器。我们逐段进行分析。

11.16.2.1. 页面的 URL

// =========================================================================
// Controllers/ScheduleController.cs
// -------------------------------------------------------------------------
// 日程页面:选择医生和日期,显示该医生当天的日程
// 以及预约的创建与取消。
//
//   GET /schedule?doctorId=1&day=2026-09-23 页面
//   GET /schedule?doctorId=1&day=2026-09-23&book=7 同一页面,并
//                                                          打开时间段 7 的
//                                                          预约对话框
//   POST /schedule/book 创建预约
//   POST /schedule/cancel 取消预约
//
// 整个页面由其 URL 描述:可以重新加载、加入书签,
// 也可以使用浏览器的"后退"按钮,而无需任何一行
// JavaScript。
//
// 每种用户能看到什么、能做什么:
//
//   | 角色 | 已预约时间段的显示 | 预约 | 取消 |
//   |:-:|:-:|:-:|:-:|
//   | ADMIN, DOCTOR | 患者姓名 | 为患者预约 | 是 |
//   | | | 从列表中选择 | |
//   | USER (患者) | "已预约",或其本人的姓名 | 仅为自己预约,若 | 否 (*) |
//   | | (若是其本人的预约) | 他们没有 | |
//   | | | 未来的预约 | |
//
//   (*) 患者在其"我的空间"页面中取消自己的预约。
//
// 保密性:对于患者,其他患者的姓名并不是
// 仅仅在视图中隐藏,而是根本不会放入传给视图的模型中。
// 因此发送到浏览器的 HTML 不包含这些姓名,
// 连隐藏的也没有(否则只需"查看页面源代码"就会暴露它们)。
//
// 不能预约过去的时间:只有今天和之后的日期才会
// 出现"预约"按钮
// (业务层无论如何也会拒绝)。
//
// 类上的 [Authorize]:所有操作都要求用户已登录(相当于 @UseGuards(JwtAuthGuard))。
// 操作上的 [Authorize(Roles =
// "...")] 额外要求具有所列角色之一(RolesGuard +
// @Roles)。没有有效令牌:返回 /login;角色不足:403 页面。
// =========================================================================

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RdvMedecins.Auth;
using RdvMedecins.Entities;
using RdvMedecins.Business;
using RdvMedecins.Models;
using RdvMedecins.Web;

namespace RdvMedecins.Controllers;

[Authorize]
[Route("schedule")]
public class ScheduleController(ApplicationModel application) : Controller
{
    // 控制器所了解的用户信息,用来决定显示什么
    private record Rights(
        bool Manager, // ADMIN 或 DOCTOR
        Client? Patient, // 已登录的客户(USER 角色),否则为 null
        bool PatientCanBook); // 没有未来预约的 USER
  • 第 7–12 行:页面的路由。请注意,预约窗口不是由 [JavaScript] 打开的:它是 URL 的一个参数([book=7]),指示服务器在渲染页面时打开该窗口。因此,“预约”按钮只是一个链接。整个页面由其 URL 描述:可以重新加载、加入书签,或使用浏览器的“后退”按钮;
  • 第 18–28 行:每个角色能看到什么、能做什么。这张表是页面的“规格说明”:控制器的其余部分负责实现它;
  • 第 30–33 行:隐私规则,我们稍后会再讨论:其他患者的姓名不是由视图隐藏的,而是根本不会发送到浏览器;
  • 第 55–57 行:类上的 [[Authorize]] 表示所有操作都要求用户已登录,无论其角色如何(参见示例 25)。[[Route("schedule")]] 是该控制器所有路由的前缀(参见示例 02)。控制器通过注入(参见示例 06)经由其[ApplicationModel]主构造函数接收该服务:写在类名后括号中的参数可在其所有方法中访问;
  • 第 60–63 行:控制器对已登录用户的了解,每次请求计算一次(参见下文的 [RightsAsync])。这是一个私有的 [record],声明在类内部:只有该类使用它。[Manager] 对 ADMIN 或 DOCTOR 为 true; [Patient] 仅对客户(角色 USER)填充。

11.16.2.2. GET /schedule

    // -----------------------------------------------------------------------
    // GET /schedule
    // URL 参数按原始方式读取(Request.Query),以区分
    // 参数缺失与参数为空(?doctorId=)。
    // -----------------------------------------------------------------------
    [HttpGet("")]
    public async Task<IActionResult> Show()
    {
        string? error = null;
        var user = User.CurrentUser()!;
        var rights = await RightsAsync(user);

        // 日期:URL 中的日期(若有效),否则为今天
        var day = Dates.Today();
        if (Request.Query.TryGetValue("day", out var rawDay))
        {
            if (WebDates.IsValidDate(rawDay, out var requestedDay))
            {
                day = requestedDay;
            }
            else
            {
                error = "ERRORS.INVALID_DATE";
            }
        }
        var dayBookable = day >= Dates.Today();

        // 医生:URL 中的医生;若没有,则对已登录的医生取其本人
        var doctorId = Input.PositiveInteger(Request.Query["doctorId"]);
        if (!Request.Query.ContainsKey("doctorId") && user.Role == Role.DOCTOR)
        {
            doctorId = application.GetDoctorByUserId(user.UserId)?.Id;
        }

        var doctors = (await application.GetAllDoctorsAsync())
            .Select(d => Option(d, d.Id == doctorId))
            .ToList();

        // 日程,前提是已选定医生(且日期有效)
        ScheduleView? schedule = null;
        if (doctorId is int id && error is null)
        {
            var doctorSchedule = await application.GetDoctorDayScheduleAsync(id, day);
            if (doctorSchedule is null)
            {
                error = "ERRORS.DOCTOR_NOT_FOUND";
            }
            else
            {
                var rows = doctorSchedule.DoctorDaySlots.Select(dds =>
                {
                    var (slot, appointment) = (dds.Slot, dds.Appointment);
                    var free = appointment is null;
                    // 已登录患者的预约?
                    var mine = appointment is not null && rights.Patient is not null && appointment.ClientId == rights.Patient.Id;
                    return new ScheduleRowView
                    {
                        SlotId = slot.Id,
                        Time = WebDates.Time(slot),
                        Free = free,
                        // 保密的关键点:患者只会得到其本人预约的姓名;
                        // 对于其他预约则为 null(视图显示"已预约")
                        Patient = appointment is not null && (rights.Manager || mine) ? Labels.Label(appointment.Client) : null,
                        Mine = mine,
                        Bookable = free && dayBookable && (rights.Manager || rights.PatientCanBook),
                        BookUrl = ScheduleUrl(id, day, slot.Id),
                        AppointmentId = appointment is not null && rights.Manager ? appointment.Id : null,
                    };
                }).ToList();
                schedule = new ScheduleView(Labels.Label(doctorSchedule.Doctor), WebDates.Iso(day), rows);
            }
        }
  • 第 6–7 行:路由 [GET /schedule] (控制器前缀,后跟空字符串)。该操作没有参数:它自动把 URL 作为 [Request.Query] 读取(参见示例 05)。模型绑定会把 [int? doctorId] 参数在缺失或为空时都转换为 [null];然而这两种情况必须加以区分(见下文);
  • 第 10–11 行:已登录的用户及其权限。[CurrentUser()] 是定义在 [Auth/ConnectedUser.cs] 中的扩展方法(参见示例 06):它读取令牌的声明并将其转换为类型化对象。[!] 告知编译器结果不是 [null]:这是确定的,因为 [[Authorize]] 已经过滤掉了未经身份验证的请求;
  • 第 14–26 行:所请求的日期(如果有效);否则为今天。如果参数 [TryGetValue] 缺失,[false] 就会返回 [day]:此时返回今天,不产生消息。如果存在但无效([day=2026-02-30]),则会生成错误消息。预约只能从今天开始进行([dayBookable]);
  • 第 29–32 行:所请求的医生。[Input.PositiveInteger](文件夹 [Web])返回严格正整数,如果值缺失、为空或无效,则返回 [null] 。如果 URL 中[doctorId] 参数缺失,已登录的医生会看到自己的日程:这是其主页。如果它为空([doctorId=],即列表中的“-- choose a doctor --”选项),则不显示任何日程;
  • 第 35–37 行:医生下拉列表中的选项,从 [ApplicationModel] 的缓存中读取;所请求医生对应的选项被选中(参见文件末尾的 [Option] 函数和示例 18);
  • 第 40–46 行:只有在选择了医生且日期有效时才计算日程。[doctorId is int id] 检查该值(类型为 [int?])不是 [null],并把它的值存入新变量 [id],其类型为 [int]。未知的医生 ID 会触发一条消息,而不是错误页面。
  • 第 50–56 行:业务层计算出的日程(来自 [Domain] 文件夹的 [DoctorDaySchedule] 对象)被转换为数组元素,每个时间段一个。[var (slot, appointment) = ...] 把一对值分解为两个变量。[mine] 决定该预约是否属于已登录的患者;
  • 第 58–59 行:视图只接收已经格式化的数据([8:00 - 8:20]);它不再需要计算任何东西;
  • 第 63 行:应用程序的隐私控制。只有对管理员,或对于预约所属的患者,患者姓名才会放入模型中。对其他所有人,模型中包含 [null],视图显示“已预约”。姓名并不是简单地由视图隐藏:它从未发送到浏览器,“查看页面源代码”也无法暴露它;
  • 第 65–67 行:视图必须显示的内容,由控制器决定:“预约”按钮(时间段可用、日期未过期,并且用户有权预约)、其链接(页面的 URL,带有 [book]),以及“取消”按钮([AppointmentId] 仅对管理员填充)。视图不做任何决定:它只遵循这些指令;
  • 第 70 行:完整的日程:医生、日期和各行。

11.16.2.3. 预约窗口与视图模板

        // 预约对话框:仅当请求的时间段
        // 可由该用户预约时才显示
        BookingView? booking = null;
        var slotId = Input.PositiveInteger(Request.Query["book"]);
        var row = schedule?.Rows.FirstOrDefault(r => r.SlotId == slotId && r.Bookable);
        if (row is not null)
        {
            booking = new BookingView
            {
                SlotId = row.SlotId,
                Time = row.Time,
                Clients = rights.Manager
                    ? (await application.GetAllClientsAsync()).Select(c => Option(c, false)).ToList()
                    : [],
                Patient = rights.Patient is not null ? Labels.Label(rights.Patient) : null,
            };
        }

        return View("Schedule", new ScheduleModel
        {
            PageTitle = "SCHEDULE.PAGE_TITLE",
            Doctors = doctors,
            DoctorId = doctorId,
            Day = WebDates.Iso(day),
            Schedule = schedule,
            Booking = booking,
            BackUrl = doctorId is int dId ? ScheduleUrl(dId, day) : "/schedule",
            Info = rights.Patient is not null && !rights.PatientCanBook ? "SCHEDULE.ALREADY_BOOKED_INFO" : null,
            Error = error,
        });
    }
  • 第 3–5 行:URL 请求预约的时间段([book=7])。它必须出现在所显示的日程中,并且能被该用户预约:手工构造的 URL(过去的时间段、已被预约的时间段,或属于其他医生的时间段)不会打开该窗口。[schedule?.Rows] 在 [schedule] 为 [null] 时等于 [null] (运算符 [?.]);
  • 第 6–15 行:窗口模板。管理员从列表中选择患者(所有客户,从缓存中读取);患者为自己预约:窗口只显示其姓名。[[]] 是一个空列表;
  • 第 19–29 行:页面模板。它的类([ScheduleModel], [ScheduleView], [ScheduleRowView], [BookingView], [OptionView])定义在 [Models/ViewModels.cs] 中;[PageTitle] 和 [Error] 派生自它们共同的父类 [ViewModel]。[PageTitle] 与所有文本一样,是一个翻译键;
  • 第 27 行:所显示日历的地址,不带预约窗口——这是关闭窗口的按钮的地址;
  • 第 28 行:给已有即将到来的预约的患者的提示消息:它说明了为什么他们看不到“预约”按钮。

11.16.2.4. POST /schedule/book

    // -----------------------------------------------------------------------
    // POST /schedule/book 字段:doctorId、day、slotId、clientId
    //
    // 对于患者(USER),clientId 字段会被忽略:他们始终为自己预约。
    // 若信任浏览器发送的字段,狡猾的患者就可能以
    // 他人的名义预约。
    //
    // "Post / Redirect / Get" 模式:无论结果如何,这里都不
    // 构建页面,而是放入一条闪现消息并重定向
    // 到日程页(见 Web/Flash.cs)。
    // -----------------------------------------------------------------------
    [HttpPost("book")]
    [Authorize(Roles = "ADMIN,DOCTOR,USER")]
    public async Task<IActionResult> Book(
        [FromForm] string? doctorId,
        [FromForm] string? day,
        [FromForm] string? slotId,
        [FromForm] string? clientId)
    {
        if (!ReadScheduleRequest(doctorId, day, out var docId, out var requestedDay)
            || Input.PositiveInteger(slotId) is not int sltId)
        {
            return BadRequest(); // -> "无效请求"页面(见 Program.cs)
        }

        Client? client;
        if (User.IsInRole(nameof(Role.USER)))
        {
            client = await Patient.ConnectedPatientAsync(application, User);
        }
        else
        {
            if (Input.PositiveInteger(clientId) is not int cliId)
            {
                // 未选择患者:重新打开预约对话框
                Flash.Put(HttpContext, FlashType.Danger, "ERRORS.CHOOSE_PATIENT");
                return Redirect(ScheduleUrl(docId, requestedDay, sltId));
            }
            client = await application.GetClientByIdAsync(cliId);
        }

        var slot = await application.GetSlotByIdAsync(sltId);
        if (client is null)
        {
            Flash.Put(HttpContext, FlashType.Danger, "ERRORS.PATIENT_NOT_FOUND");
        }
        else if (slot is null || slot.DoctorId != docId)
        {
            Flash.Put(HttpContext, FlashType.Danger, "ERRORS.SLOT_NOT_FOUND");
        }
        else
        {
            try
            {
                // 规则(不在过去、每位患者只能有一个未来预约、
                // 时间段空闲)由业务层检查
                await application.AddAppointmentAsync(requestedDay, slot, client);
                Flash.Put(HttpContext, FlashType.Success, "SCHEDULE.BOOKED");
            }
            // "when":一个异常过滤器。规则相同,但当预约人就是患者本人时,消息使用第二
            // 人称("您
            // 已经有……"而不是"该患者……")
            catch (BusinessException e) when (e.Key == "ERRORS.PATIENT_HAS_UPCOMING_APPOINTMENT" && User.IsInRole(nameof(Role.USER)))
            {
                Flash.Put(HttpContext, FlashType.Danger, "SCHEDULE.ALREADY_BOOKED_INFO");
            }
            // 任何其他 BusinessException 都会变成闪现消息;其他
            // 异常(真正的异常情况)不会被捕获:显示 500 页面
            catch (BusinessException e)
            {
                Flash.Put(HttpContext, FlashType.Danger, e.Key, new Dictionary<string, string>(e.Params));
            }
        }
        return Redirect(ScheduleUrl(docId, requestedDay));
    }
  • 第 12–13 行:操作上的 [[Authorize(Roles = ...)]] 会叠加到类的 [[Authorize]] 之上:三种角色都可以预约(参见示例 26)。在这里,该特性不施加更多限制;它记录了这条规则,并且在出现第四种角色时能保护该操作;
  • 第 15–18 行:预约窗口表单中的字段(参见示例 11)。它们以字符串形式接收,然后被小心地转换;
  • 第 20–23 行:医生和日期是表单中的隐藏字段;它们使用户能够返回所显示的日历。如果它们无效,说明请求并非来自我们的页面:而是手工构造的。[BadRequest()] 返回没有内容的 400 响应,由 [UseStatusCodePagesWithReExecute] 中间件将其转换为错误页面(参见示例 24)。[is not int sltId] 与 [is int] 相反:如果值为 [null],则为 true;否则,[sltId] 接收该值;
  • 第 27–29 行:对于患者,[clientId] 字段会被忽略——系统始终为患者本人预约。如果依赖浏览器发送的这个字段,恶意患者就可以以他人的名义预约。[Patient.ConnectedPatientAsync](文件夹 [Web])使用令牌识别客户;[nameof(Role.USER)] 就是字符串 ["USER"],由编译器验证;
  • 第 33–39 行:没有选择患者的管理者会被重定向到预约窗口(带有 [book] 的 URL),并附带一条弹出的错误消息。[Flash.Put](文件夹 [Web])把消息存储在 [TempData] 中(参见示例 20);
  • 第 42–49 行:患者必须存在,时间段也必须存在,并且属于日历中的医生:不能把属于某位医生的时间段预约给另一位医生;
  • 第 57–58 行:业务规则(不在过去、时间段可用、每位患者只能有一个即将到来的预约)由业务逻辑层验证,被拒绝时它会抛出 [BusinessException];
  • 第 63–65 行:[when] 为 [catch] 添加条件:这是 [C#] 异常过滤器。只有条件为 true 时,这个块才会捕获 [BusinessException]:对于患者,消息“该患者已有预约”会被替换为第二人称的消息。否则,异常会继续传递到下一个 [catch];
  • 第 69–71 行:任何其他 [BusinessException] 都会变成闪存消息,连同其键和参数([e.Params] 是只读字典:会为它创建一个副本,类型为 [Flash.Put] 所期望的类型)。其他异常不会被捕获:这些是真正的错误,会导致 500 错误页面;
  • 第 74 行:PRG 模式:无论结果如何,都会显示闪存消息,并将用户重定向到日历,由日历显示该消息。在 [NestJS] 版本中,由一个工具函数负责这种业务错误的转换;在这里,两个 [catch] 块就足够了。

11.16.2.5. POST /schedule/cancel

    // -----------------------------------------------------------------------
    // POST /schedule/cancel 字段:appointmentId、doctorId、day
    // (患者在"我的空间"而不是在这里取消其本人的预约)
    // -----------------------------------------------------------------------
    [HttpPost("cancel")]
    [Authorize(Roles = "ADMIN,DOCTOR")]
    public async Task<IActionResult> Cancel([FromForm] string? appointmentId, [FromForm] string? doctorId, [FromForm] string? day)
    {
        if (!ReadScheduleRequest(doctorId, day, out var docId, out var requestedDay)
            || Input.PositiveInteger(appointmentId) is not int id)
        {
            return BadRequest();
        }
        var appointment = await application.GetAppointmentByIdAsync(id);
        if (appointment is null)
        {
            // 已被取消(被他人取消,或重复点击)
            Flash.Put(HttpContext, FlashType.Danger, "ERRORS.APPOINTMENT_NOT_FOUND");
        }
        else
        {
            await application.DeleteAppointmentAsync(appointment);
            Flash.Put(HttpContext, FlashType.Success, "SCHEDULE.CANCELLED");
        }
        return Redirect(ScheduleUrl(docId, requestedDay));
    }
  • 第 5–7 行:取消仅限管理员;患者从“我的区域”取消自己的预约(参见 [PatientAreaController])。发送此请求的患者会收到 403 页面;
  • 第 9–12 行:与预约时相同的检查;
  • 第 14–18 行:已被取消的预约(因双击或由另一位管理员取消)会触发错误消息,而不是错误页面;
  • 第 22–25 行:删除,随后是 PRG 模式。

11.16.2.6. 权限与工具函数

    // -----------------------------------------------------------------------
    // 谁已登录,他在此页面上被允许做什么?
    // -----------------------------------------------------------------------
    private async Task<Rights> RightsAsync(ConnectedUser user)
    {
        if (user.Role != Role.USER)
        {
            return new Rights(Manager: true, Patient: null, PatientCanBook: false);
        }
        var patient = await Patient.ConnectedPatientAsync(application, User);
        var upcoming = await application.GetClientUpcomingAppointmentsAsync(patient.Id);
        return new Rights(Manager: false, patient, PatientCanBook: upcoming.Count == 0);
    }

    // 工具函数

    // 隐藏的 doctorId / day 字段,两个 POST 表单共用
    private static bool ReadScheduleRequest(string? rawDoctorId, string? rawDay, out int doctorId, out DateOnly day)
    {
        doctorId = Input.PositiveInteger(rawDoctorId) ?? 0;
        return WebDates.IsValidDate(rawDay, out day) && doctorId > 0;
    }

    private static string ScheduleUrl(int doctorId, DateOnly day, int? book = null)
    {
        var url = $"/schedule?doctorId={doctorId}&day={WebDates.Iso(day)}";
        return book is null ? url : $"{url}&book={book}";
    }

    private static OptionView Option(Person p, bool selected) => new(p.Id, Labels.Label(p), selected);
}
  • 第 4–12 行:管理员拥有全部权限;患者在没有即将到来的预约时可以预约。命名参数([Manager: true])使对 [record] 构造函数的调用易于阅读;
  • 第 18–21 行:读取 POST 表单共有的两个隐藏字段。[out] 参数是方法的额外结果:它返回一个布尔值(字段是否有效?),并通过其 [out] 参数返回转换后的值。这正是 [int.TryParse] 的工作方式;
  • 第 24–27 行:医生某一天的日程的 URL,可能带有已打开的预约窗口。所有控制器的重定向都通过此函数生成:页面的 URL 只在一个地方编写;
  • 第 30 行:下拉列表选项(ID、标签、选中状态),医生和客户通用:参数的类型为 [Person],即这两个实体的父类。

11.16.3. Controllers/PersonsControllerBase.cs

// =========================================================================
// Controllers/PersonsControllerBase.cs
// -------------------------------------------------------------------------
// 医生的管理和客户的管理(仅限 ADMIN)是
// 相同的:同样的列表、同样的表单、同样的规则。与其
// 把同样的操作写两遍,不如在这个
// 抽象泛型类中只写一次,由 DoctorsController
// ([Route("doctors")])和 ClientsController ([Route("clients")])继承。每个
// 子类只需提供其"配置":要调用哪些方法、
// 要显示哪些标签。
//
// 放在这里的路由([HttpGet("add")]……)会被继承,
// 并补全子类的路由。因此每个子类都得到:
//
//   GET /doctors 列表
//   GET /doctors/add 空表单
//   POST /doctors/add 创建
//   GET /doctors/{id}/edit 预填充的表单
//   POST /doctors/{id}/edit 更新
//   POST /doctors/{id}/delete 删除
//
// (/clients 下的 URL 同理)。视图也是共用的:
// Views/Persons/List.cshtml 和 Views/Persons/Form.cshtml。
//
// MVC 绝不会把抽象类当作控制器:只有
// 它的具体子类才会。
// =========================================================================

using Microsoft.AspNetCore.Mvc;
using RdvMedecins.Entities;
using RdvMedecins.Business;
using RdvMedecins.Models;
using RdvMedecins.Web;

namespace RdvMedecins.Controllers;

// 每个子类必须提供的内容
public record PersonsConfig<T>(
    string Url, // "/doctors" 或 "/clients"
    PersonKeys Keys,
    Func<Task<List<T>>> List,
    Func<int, Task<T?>> Find,
    Func<PersonData, Task<T>> Add,
    Func<int, PersonData, Task<T>> Edit,
    Func<int, Task> Delete) where T : Person;

public abstract class PersonsControllerBase<T>(ApplicationModel application) : Controller where T : Person
{
    protected ApplicationModel Application { get; } = application;

    protected abstract PersonsConfig<T> Config { get; }

    // -----------------------------------------------------------------------
    // GET /doctors(或 /clients)
    // -----------------------------------------------------------------------
    [HttpGet("")]
    public async Task<IActionResult> List()
    {
        var persons = await Config.List();
        return View("~/Views/Persons/List.cshtml", new PersonListModel
        {
            PageTitle = Config.Keys.Title,
            Keys = Config.Keys,
            AddUrl = $"{Config.Url}/add",
            Persons = persons
                .Select(p => new PersonView(p.Title, p.FirstName, p.LastName, p.User?.Login ?? "",
                    $"{Config.Url}/{p.Id}/edit", $"{Config.Url}/{p.Id}/delete"))
                .ToList(),
        });
    }

    // -----------------------------------------------------------------------
    // GET /doctors/add
    // -----------------------------------------------------------------------
    [HttpGet("add")]
    public IActionResult AddForm() => ShowForm(null, new PersonValues());

    // -----------------------------------------------------------------------
    // POST /doctors/add
    // [form] 已由 MVC 填充并验证:ModelState 说明
    // 输入是否正确。
    // -----------------------------------------------------------------------
    [HttpPost("add")]
    public async Task<IActionResult> Add(PersonForm form)
    {
        if (!ModelState.IsValid)
        {
            return ShowForm(null, EnteredValues(form), Validation.ErrorsOf(ModelState));
        }
        try
        {
            var person = await Config.Add(Data(form));
            Flash.Put(HttpContext, FlashType.Success, Config.Keys.Added, MessageParams(person));
            return Redirect(Config.Url);
        }
        catch (BusinessException e)
        {
            return ShowBusinessError(null, EnteredValues(form), e);
        }
    }

    // -----------------------------------------------------------------------
    // GET /doctors/{id}/edit
    // {id:int}:"路由约束",/doctors/abc/edit 不
    // 匹配任何路由(404 页面)
    // -----------------------------------------------------------------------
    [HttpGet("{id:int}/edit")]
    public async Task<IActionResult> EditForm(int id)
    {
        var person = await Config.Find(id);
        if (person is null)
        {
            return NotFound();
        }
        return ShowForm(id, new PersonValues
        {
            Title = person.Title,
            FirstName = person.FirstName,
            LastName = person.LastName,
            Login = person.User?.Login ?? "",
            Version = person.Version,
        });
    }

    // -----------------------------------------------------------------------
    // POST /doctors/{id}/edit
    // -----------------------------------------------------------------------
    [HttpPost("{id:int}/edit")]
    public async Task<IActionResult> Edit(int id, PersonForm form)
    {
        if (!ModelState.IsValid)
        {
            return ShowForm(id, EnteredValues(form), Validation.ErrorsOf(ModelState));
        }
        try
        {
            var person = await Config.Edit(id, Data(form));
            Flash.Put(HttpContext, FlashType.Success, Config.Keys.Edited, MessageParams(person));
            return Redirect(Config.Url);
        }
        catch (BusinessException e)
        {
            return ShowBusinessError(id, EnteredValues(form), e);
        }
    }

    // -----------------------------------------------------------------------
    // POST /doctors/{id}/delete
    // ("确定吗?"确认由浏览器在发送表单之前询问,
    // 见 wwwroot/js/app.js)
    // -----------------------------------------------------------------------
    [HttpPost("{id:int}/delete")]
    public async Task<IActionResult> Delete(int id)
    {
        var person = await Config.Find(id);
        try
        {
            await Config.Delete(id);
            Flash.Put(HttpContext, FlashType.Success, Config.Keys.Deleted, MessageParams(person));
        }
        catch (BusinessException e)
        {
            Flash.Put(HttpContext, FlashType.Danger, e.Key, new Dictionary<string, string>(e.Params));
        }
        return Redirect(Config.Url);
    }

    // 私有方法

    // id 为 null:创建表单;否则:编辑表单
    private ViewResult ShowForm(
        int? id,
        PersonValues values,
        Dictionary<string, string>? errors = null,
        string? error = null,
        IEnumerable<string>? otherFields = null)
    {
        var creating = id is null;
        return View("~/Views/Persons/Form.cshtml", Validation.Prepare(
            new PersonFormModel
            {
                PageTitle = creating ? Config.Keys.Add : Config.Keys.Edit,
                Creating = creating,
                Action = creating ? $"{Config.Url}/add" : $"{Config.Url}/{id}/edit",
                ListUrl = Config.Url,
                Values = values,
            },
            errors, error, otherFields));
    }

    // 某条业务规则拒绝了写入:我们重新显示表单,
    // 并附上用户的输入和业务层的消息
    private IActionResult ShowBusinessError(int? id, PersonValues values, BusinessException e)
    {
        if (e.Key is "ERRORS.DOCTOR_NOT_FOUND" or "ERRORS.PATIENT_NOT_FOUND")
        {
            // 在此期间已被另一位 ADMIN 删除:返回列表
            Flash.Put(HttpContext, FlashType.Danger, e.Key);
            return Redirect(Config.Url);
        }
        // 消息放在页面底部;若有相关字段,则用红色
        // 框出,让用户立刻看到该修正什么
        return ShowForm(id, values, null, e.Key, Validation.BusinessErrorFields.GetValueOrDefault(e.Key));
    }

    // 用户输入的内容(不含密码:绝不会把它回传给浏览器)
    private static PersonValues EnteredValues(PersonForm f) => new()
    {
        Title = f.Title ?? "",
        FirstName = f.FirstName ?? "",
        LastName = f.LastName ?? "",
        Login = f.Login ?? "",
        Version = f.Version,
    };

    // 已验证的表单 -> 业务层所需的数据
    private static PersonData Data(PersonForm f) => new()
    {
        Title = f.Title!,
        LastName = f.LastName!,
        FirstName = f.FirstName!,
        Login = f.Login,
        Password = f.Password,
        Version = f.Version,
    };

    // "已添加 / 已更新 / 已删除"消息中的 {name} 和 {login}
    private static Dictionary<string, string> MessageParams(Person? person) => person is null
        ? new() { ["name"] = "", ["login"] = "" }
        : new() { ["name"] = $"{person.FirstName} {person.LastName}", ["login"] = person.User?.Login ?? "" };
}

医生和客户的管理是相同的。我们不编写两个相似的控制器,而是在一个抽象的泛型父类中只编写一次它们的操作。我们来说明这段代码:

  • 第 15–20 行:医生的路由;在 [/clients] 中也存在相同的路由;
  • 第 22–23 行:视图也是共享的(文件夹 [Views/Persons]);
  • 第 25–26 行:MVC 只接受具体类作为控制器:只有 [DoctorsController] 和 [ClientsController] 接收请求;
  • 第 38–45 行:每个子类提供的配置:基础 URL、文本(翻译键,在 [record] 和 [PersonKeys] 中分组,位于 [Models/ViewModels.cs]),以及用于列出、搜索、添加、修改和删除时要调用的函数。[Func<int, Task<T?>>] 是接受一个 [int] 并返回 [Task<T?>] 的函数的类型:方法就是这样存储在属性中,供以后调用的。[where T : Person] 是对泛型类型的约束:[T] 将是 [Doctor] 或 [Client],即派生自 [Person] 的两个类;因此代码可以使用 [p.FirstName] 或 [p.User],它们对所有人员都是通用的;
  • 第 47 行:父类,它是泛型的(参见示例 22 中的 [ViewPage<TModel>] 类)并且是抽象的。它通过主构造函数接收 [ApplicationModel] ,并通过受保护的属性 [Application] ([protected]:只对子类可见)将其传递给子类;
  • 第 51 行:抽象属性:每个子类都必须定义它;
  • 第 56–69 行:列表。设置在父类方法上的路由特性会被继承:与子类的 [[Route("doctors")]] 结合,得到 [GET /doctors]。对每个人员,模型都包含其“编辑”和“删除”按钮的 URL。[p.User?.Login ?? ""]:关联账户的登录名,如果该人员没有账户则为空字符串;
  • 第 60 行:视图通过其完整路径指定。如果只使用名称,MVC 会在控制器的文件夹中查找它([Views/Doctors] 或 [Views/Clients],参见示例 13),而该视图是两者共享的;
  • 第 75–76 行:空表单;
  • 第 83–98 行:添加,分三步进行,与示例 28 相同。参数 [form] 在调用之前已由 MVC 填充并验证(参见示例 19):无效的输入会重新显示表单,显示已输入的值以及每个错误字段下方的消息;有效的输入会传给业务层,然后浏览器被重定向到列表,并带有闪存消息(PRG);业务层的拒绝(同名、登录名已被使用)会重新显示表单;
  • 第 107–121 行:预填充的修改表单。路由约束 [:int] (参见示例 02)只接受整数标识符:[/doctors/abc/edit] 不对应任何路由,结果是 404 页面([ParseIntPipe] 在 [NestJS] 中则会得到 400 错误)。不存在的人员同样得到 404。版本号是表单中的隐藏字段,将用于乐观锁(参见示例 28);
  • 第 128–143 行:更新,遵循与插入相同的模式;
  • 第 152–165 行:删除。事先检索该人员,以便在确认消息中显示其姓名。业务层的拒绝(例如,医生有预约)会在列表页面上产生闪存错误消息;
  • 第 171–188 行:创建时的表单([id] 等价于 [null]),与修改时一样:只有标题和提交地址([Action])不同。[Validation.Prepare](文件夹 [Web])为模板填充各字段的错误消息、页脚消息以及要以红色高亮的字段;
  • 第 193–203 行:已被(另一位管理员)删除的人员会再次出现在列表中;其他业务错误会重新显示表单,并带有页脚消息,相关字段以红色高亮([Validation.BusinessErrorFields] 把每个错误代码与其对应的字段关联起来:同名时为 [firstName] 和 [lastName] )。[is "A" or "B"] 把一个值与多个常量进行比较;
  • 第 207–213 行:要重新显示的值——绝不包括密码;
  • 第 217–224 行:传递给业务层的数据。[!] 字段不会有风险:验证已经确认了这些字段的存在;
  • 第 228–230 行:成功消息中的 [{name}] 和 [{login}] 参数:人员的名和姓,以及其登录名。

11.16.4. Controllers/DoctorsController.cs

// =========================================================================
// Controllers/DoctorsController.cs
// -------------------------------------------------------------------------
// 医生管理(仅限 ADMIN 角色)。所有操作都
// 继承自 PersonsControllerBase:这里只需说明要调用
// 什么,以及要显示哪些标签。
//
// 放在类上的 [Authorize(Roles = "ADMIN")] 适用于它的所有
// 操作,包括继承来的操作。
// =========================================================================

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RdvMedecins.Entities;
using RdvMedecins.Models;
using RdvMedecins.Web;

namespace RdvMedecins.Controllers;

[Authorize(Roles = "ADMIN")]
[Route("doctors")]
public class DoctorsController(ApplicationModel application) : PersonsControllerBase<Doctor>(application)
{
    protected override PersonsConfig<Doctor> Config => new(
        Url: "/doctors",
        Keys: new PersonKeys(
            Title: "DOCTORS.TITLE",
            Add: "DOCTORS.ADD",
            Edit: "DOCTORS.EDIT",
            Empty: "DOCTORS.EMPTY",
            ConfirmDelete: "DOCTORS.DELETE_CONFIRM",
            Added: "DOCTORS.ADDED",
            Edited: "DOCTORS.UPDATED",
            Deleted: "DOCTORS.DELETED"),
        List: Application.GetAllDoctorsAsync,
        Find: Application.GetDoctorByIdAsync,
        Add: Application.AddDoctorAsync,
        Edit: Application.EditDoctorAsync,
        Delete: Application.DeleteDoctorAsync);
}
  • 第 20–22 行:仅限 ADMIN。设置在类上的特性适用于它的所有操作,包括继承的操作。该控制器继承自 [PersonsControllerBase<Doctor>]:父类的类型 [T] 变为 [Doctor]。它的主构造函数把 [application] 传递给父类的构造函数。(在 [TypeScript] 中,必须编写显式构造函数,才能让 [NestJS] 知道要注入什么;这里不需要这样做);
  • 第 24–34 行:配置。[override] 重新定义父类的抽象属性;[=>] 把它变成计算属性,每次读取时都会创建对象。命名参数([Url:]、[Keys:]……)使这份列表易于阅读;
  • 第 35–39 行:要调用的函数,它们是 [ApplicationModel] 的方法。[Application.GetAllDoctorsAsync] 不带括号书写,并不调用该方法:它只是引用该方法,编译器会把它转换为所需类型 [Func] 的值。

11.16.5. Controllers/ClientsController.cs

// =========================================================================
// Controllers/ClientsController.cs
// -------------------------------------------------------------------------
// 客户(诊所的患者)管理,仅限 ADMIN 角色。
// 原理与 DoctorsController 相同(见其注释)。
// =========================================================================

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RdvMedecins.Entities;
using RdvMedecins.Models;
using RdvMedecins.Web;

namespace RdvMedecins.Controllers;

[Authorize(Roles = "ADMIN")]
[Route("clients")]
public class ClientsController(ApplicationModel application) : PersonsControllerBase<Client>(application)
{
    protected override PersonsConfig<Client> Config => new(
        Url: "/clients",
        Keys: new PersonKeys(
            Title: "CLIENTS.TITLE",
            Add: "CLIENTS.ADD",
            Edit: "CLIENTS.EDIT",
            Empty: "CLIENTS.EMPTY",
            ConfirmDelete: "CLIENTS.DELETE_CONFIRM",
            Added: "CLIENTS.ADDED",
            Edited: "CLIENTS.UPDATED",
            Deleted: "CLIENTS.DELETED"),
        List: Application.GetAllClientsAsync,
        Find: Application.GetClientByIdAsync,
        Add: Application.AddClientAsync,
        Edit: Application.EditClientAsync,
        Delete: Application.DeleteClientAsync);
}

同样的控制器,用于客户:路由不同,翻译键不同,使用的 [ApplicationModel] 方法也不同。

11.16.6. Controllers/RegistrationController.cs

// =========================================================================
// Controllers/RegistrationController.cs
// -------------------------------------------------------------------------
// "创建患者账户":还没有账户的患者
// 自行创建账户。
// 非受保护路由(根据定义,此时还没有账户):
//
//   POST /register/access 身份验证页面的"创建患者账户"按钮:
//                             检查该页面的验证码,
//                             然后打开表单
//   GET /register 表单
//   POST /register 创建,然后返回登录页面
//
// 该流程由唯一的一个验证码来防范机器人,
// 即身份验证页面的验证码:
//   1. "创建患者账户"按钮把登录表单发送
//      到 /register/access;若验证码抄写正确,服务器
//      会签发一张通行证(见 Auth/RegistrationPassService.cs);
//   2. 没有有效通行证时,/register 会把用户送回
//      身份验证页面,直接输入 URL 没有用;
//   3. 通行证在创建时被消耗:解出一个验证码
//      只能创建一个账户;
//   4. 此外,每小时每个 IP 地址创建的账户数
//      也有限制(见 Auth/AttemptLimiterService.cs)。
//
// 所创建的账户与 ADMIN 在"患者"页面创建的账户完全相同
// (调用业务层的同一方法:AddClientAsync),区别在于
// 患者自己选择登录名和密码(必填,
// 并需确认)。
// =========================================================================

using Microsoft.AspNetCore.Mvc;
using RdvMedecins.Auth;
using RdvMedecins.Business;
using RdvMedecins.Models;
using RdvMedecins.Web;

namespace RdvMedecins.Controllers;

[Route("register")]
public class RegistrationController(
    ApplicationModel application,
    CaptchaService captchaService,
    AttemptLimiterService limiter,
    RegistrationPassService passes) : Controller
{
    // -----------------------------------------------------------------------
    // POST /register/access 字段:captchaId、captcha(来自
    // 身份验证页面;一并发送的 login 和 password 会被忽略)
    // -----------------------------------------------------------------------
    [HttpPost("access")]
    public IActionResult Access([FromForm] string? captchaId, [FromForm] string? captcha)
    {
        var ip = AuthController.IpAddress(HttpContext);

        // 最近从该地址创建的账户过多:无需继续
        var minutes = limiter.RegistrationBlockMinutes(ip);
        if (minutes > 0)
        {
            Flash.Put(HttpContext, FlashType.Danger, "ERRORS.TOO_MANY_ACCOUNTS", new() { ["minutes"] = minutes.ToString() });
            return Redirect("/login");
        }

        // 验证码缺失或错误:返回身份验证页面,并附上
        // 新图片(失败计为一次登录失败)
        if (!captchaService.Verify(captchaId, captcha))
        {
            limiter.LoginFailure(ip, "");
            Flash.Put(HttpContext, FlashType.Danger, "ERRORS.CAPTCHA_BEFORE_ACCOUNT");
            return Redirect("/login");
        }

        // 验证码正确:签发通行证并打开表单
        Response.Cookies.Append(RegistrationPassService.Cookie, passes.Issue(), RegistrationPassService.GetCookieOptions());
        return Redirect("/register");
    }

    // -----------------------------------------------------------------------
    // GET /register
    // -----------------------------------------------------------------------
    [HttpGet("")]
    public IActionResult Form()
    {
        if (!HasPass())
        {
            return BackToLogin();
        }
        return Show(new PersonValues());
    }

    // -----------------------------------------------------------------------
    // POST /register
    // [form] 参数在调用之前已由 MVC 填充并验证:
    // 验证结果在 ModelState 中。
    // -----------------------------------------------------------------------
    [HttpPost("")]
    public async Task<IActionResult> Create(RegistrationForm form)
    {
        if (!HasPass())
        {
            return BackToLogin();
        }
        var ip = AuthController.IpAddress(HttpContext);
        var values = new PersonValues
        {
            Title = form.Title ?? "Mr",
            FirstName = form.FirstName ?? "",
            LastName = form.LastName ?? "",
            Login = form.Login ?? "",
        };

        // 1. 最近从该地址创建的账户是否过多?
        var minutes = limiter.RegistrationBlockMinutes(ip);
        if (minutes > 0)
        {
            return Show(values, null, "ERRORS.TOO_MANY_ACCOUNTS", null, new Dictionary<string, string> { ["minutes"] = minutes.ToString() });
        }

        // 2. 一次性返回所有输入错误(字段 + 确认项):
        //    用户可一次改正全部错误
        var errors = Validation.ErrorsOf(ModelState);
        if (!errors.ContainsKey("password") && !errors.ContainsKey("confirmation") && form.Password != form.Confirmation)
        {
            errors["confirmation"] = "ERRORS.PASSWORDS_DIFFER";
        }
        if (errors.Count > 0)
        {
            return Show(values, errors);
        }

        // 3. 创建(客户 + USER 账户,在一个事务中)
        try
        {
            // "!":我们向编译器断言这些值不为 null,
            // 这是成立的,因为验证([Required])已通过
            await application.AddClientAsync(new PersonData
            {
                Title = form.Title!,
                LastName = form.LastName!,
                FirstName = form.FirstName!,
                Login = form.Login,
                Password = form.Password,
            });
        }
        catch (BusinessException e)
        {
            // 登录名或名 + 姓已被占用:通行证仍然有效
            return Show(values, null, e.Key, Validation.BusinessErrorFields.GetValueOrDefault(e.Key));
        }

        // 4. 通行证已被使用:它不能再用来创建第二个账户
        passes.Consume(Request.Cookies[RegistrationPassService.Cookie]);
        Response.Cookies.Delete(RegistrationPassService.Cookie, new CookieOptions { Path = "/register" });
        limiter.RegistrationSuccess(ip);

        // 5. 返回登录页面,并预填登录名
        Flash.Put(HttpContext, FlashType.Success, "REGISTRATION.DONE", new() { ["login"] = form.Login! });
        return Redirect($"/login?login={Uri.EscapeDataString(form.Login!)}");
    }

    // 私有方法

    private bool HasPass() => passes.IsValid(Request.Cookies[RegistrationPassService.Cookie]);

    // 没有有效通行证:返回身份验证页面
    private RedirectResult BackToLogin()
    {
        Flash.Put(HttpContext, FlashType.Danger, "ERRORS.CAPTCHA_BEFORE_ACCOUNT");
        return Redirect("/login");
    }

    // 表单;绝不回传任何密码给浏览器
    private ViewResult Show(
        PersonValues values,
        Dictionary<string, string>? errors = null,
        string? error = null,
        IEnumerable<string>? otherFields = null,
        IReadOnlyDictionary<string, string>? errorParams = null) =>
        View("Registration", Validation.Prepare(
            new RegistrationModel { PageTitle = "REGISTRATION.TITLE", Values = values },
            errors, error, otherFields, errorParams));
}

我们来说明这段代码:

  • 第 14–24 行:防范机器人,分四步。验证码(CAPTCHA)和尝试次数限制器已在示例 27 中介绍;
  • 第 40–45 行:该控制器没有 [[Authorize]] 特性;它的页面对所有人开放。它通过注入接收四个服务;
  • 第 51–52 行:登录页面上的“创建患者账户”按钮把登录表单发送到此地址(特性 [formaction];参见示例 20)。只读取验证码字段;
  • 第 54 行:浏览器的 IP 地址,通过 [AuthController] 的静态方法获得;
  • 第 57–61 行:最近一小时内从此地址创建的账户过多:用户被重定向到登录页面,并显示一条弹出消息,指明需要等待的分钟数。[new() { ["minutes"] = ... }] 创建消息参数字典:其类型由 [Flash.Put] 的参数推断;
  • 第 66–70 行:缺失或错误的验证码(CAPTCHA)计为一次失败的登录尝试(用户名为空):机器人无法无限次地尝试。返回登录页面会显示新的图片;
  • 第 74–75 行:验证码正确:一张通行证(参见 [Auth/RegistrationPassService.cs])被存储在 Cookie 中,浏览器被重定向到表单;
  • 第 81–88 行:表单,只有持有效通行证时才可访问。直接输入地址 [/register] 是没有意义的;
  • 第 96–97 行:创建。表单 [RegistrationForm](文件夹 [Models])已由 MVC 绑定并验证;
  • 第 99–101 行:再次验证通行证:POST 请求可能是绕过表单发送的;
  • 第 104–109 行:出错时要重新显示的值,不含密码。默认称谓为 [Mr];
  • 第 113–116 行:时间限制,在创建时再次检查;
  • 第 121–128 行:输入错误,逐字段处理(参见示例 19)。密码与其确认密码是否一致——这涉及两个字段——在这里手动验证;只有当这两个字段本身都正确时才会测试。所有错误一并报告:用户可一次性全部更正;
  • 第 136–148 行:创建客户及其 USER 账户,使用 ADMIN 所用的业务层方法。如果用户名或名字与姓氏的组合已被占用,则重新显示表单,相关字段以红色高亮;通行证仍然有效;
  • 第 152–154 行:通行证已被使用:它在服务器端被消耗,其 Cookie 被删除。要删除 Cookie,必须指定与创建时相同的路径([Path]):通行证 Cookie 只会发送到 [/register...] 的地址。最后,这次创建被计入每小时的限制。
  • 第 157–158 行:返回登录页面,用户名已预填,并显示成功消息。[Uri.EscapeDataString] 对用户名进行编码,使其可以包含在 URL 中;
  • 第 163 行:从请求的 Cookie 中读取通行证;
  • 第 166–169 行:如果没有通行证,则返回登录页面并显示一条消息;
  • 第 173–181 行:由 [Validation.Prepare] 准备的表单,与医生和客户的表单相同。[errorParams] 用于页脚消息的参数(分钟数)。

11.16.7. Controllers/PatientAreaController.cs

// =========================================================================
// Controllers/PatientAreaController.cs
// -------------------------------------------------------------------------
// 患者的个人页面(USER 角色),即登录后
// 立刻看到的页面:
//
//   GET /my-area 首页:[Manage my account]、
//                                  [View a schedule],以及其未来的预约
//   POST /my-area/cancel 取消其本人的预约
//   GET /my-account 编辑其账户的表单
//   POST /my-account 更新
//   POST /my-account/delete 删除账户(及其预约)
//
// 本控制器的黄金法则:相关患者始终是令牌中的那一位
// (Patient.ConnectedPatientAsync),绝不是浏览器发送的标识符。
// 因此患者既不能查看、修改,也不能取消
// 属于其他患者的内容,即使自己伪造请求也不行。
//
// 对账户的任何修改或删除都要求输入当前密码:
// 捡到未退出会话的人
// 既不能更改密码,也不能删除账户。当前密码
// 错误会计为登录失败(适用同一限制)。
// =========================================================================

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RdvMedecins.Auth;
using RdvMedecins.Entities;
using RdvMedecins.Business;
using RdvMedecins.Models;
using RdvMedecins.Web;

namespace RdvMedecins.Controllers;

[Authorize(Roles = "USER")]
public class PatientAreaController(
    ApplicationModel application,
    AuthService authService,
    AttemptLimiterService limiter) : Controller
{
    // -----------------------------------------------------------------------
    // GET /my-area
    // -----------------------------------------------------------------------
    [HttpGet("my-area")]
    public async Task<IActionResult> Area()
    {
        var patient = await Patient.ConnectedPatientAsync(application, User);
        var appointments = await application.GetClientUpcomingAppointmentsAsync(patient.Id);
        return View("Area", new AreaModel
        {
            PageTitle = "AREA.TITLE",
            Patient = Labels.Label(patient),
            Appointments = appointments.Select(a => new AppointmentView(
                a.Id,
                WebDates.FormatDay(a.Day),
                WebDates.Time(a.Slot),
                Labels.Label(a.Slot.Doctor),
                // 指向该医生当天日程的链接:患者在那里能看到自己的姓名
                $"/schedule?doctorId={a.Slot.Doctor.Id}&day={WebDates.Iso(a.Day)}")).ToList(),
        });
    }

    // -----------------------------------------------------------------------
    // POST /my-area/cancel 字段:appointmentId
    // -----------------------------------------------------------------------
    [HttpPost("my-area/cancel")]
    public async Task<IActionResult> CancelAppointment([FromForm] string? appointmentId)
    {
        var patient = await Patient.ConnectedPatientAsync(application, User);
        var appointment = Input.PositiveInteger(appointmentId) is int id ? await application.GetAppointmentByIdAsync(id) : null;
        // 不存在的预约和另一位患者的预约,
        // 得到相同的响应:我们不透露任何关于他人预约的信息
        if (appointment is null || appointment.ClientId != patient.Id)
        {
            Flash.Put(HttpContext, FlashType.Danger, "ERRORS.APPOINTMENT_NOT_FOUND");
        }
        else
        {
            await application.DeleteAppointmentAsync(appointment);
            Flash.Put(HttpContext, FlashType.Success, "SCHEDULE.CANCELLED");
        }
        return Redirect("/my-area");
    }

    // -----------------------------------------------------------------------
    // GET /my-account
    // -----------------------------------------------------------------------
    [HttpGet("my-account")]
    public async Task<IActionResult> AccountForm()
    {
        var patient = await Patient.ConnectedPatientAsync(application, User);
        return Show(new PersonValues
        {
            Title = patient.Title,
            FirstName = patient.FirstName,
            LastName = patient.LastName,
            Login = patient.User.Login,
            Version = patient.Version,
        });
    }

    // -----------------------------------------------------------------------
    // POST /my-account
    // -----------------------------------------------------------------------
    [HttpPost("my-account")]
    public async Task<IActionResult> EditAccount(MyAccountForm form)
    {
        var patient = await Patient.ConnectedPatientAsync(application, User);
        var values = new PersonValues
        {
            Title = form.Title ?? patient.Title,
            FirstName = form.FirstName ?? "",
            LastName = form.LastName ?? "",
            Login = form.Login ?? "",
            Version = form.Version,
        };

        var errors = Validation.ErrorsOf(ModelState);
        if (!errors.ContainsKey("password") && form.Password is not null && form.Password != form.Confirmation)
        {
            errors["confirmation"] = "ERRORS.PASSWORDS_DIFFER";
        }
        if (errors.Count > 0)
        {
            return Show(values, errors);
        }

        // 当前密码
        var passwordError = await CheckCurrentPasswordAsync(patient, form.CurrentPassword);
        if (passwordError is not null)
        {
            var (key, messageParams) = passwordError.Value;
            return Show(
                values,
                key == "ERRORS.WRONG_CURRENT_PASSWORD" ? new(StringComparer.OrdinalIgnoreCase) { ["currentPassword"] = key } : null,
                key,
                null,
                messageParams);
        }

        try
        {
            var client = await application.EditClientAsync(patient.Id, new PersonData
            {
                Title = form.Title!,
                LastName = form.LastName!,
                FirstName = form.FirstName!,
                Login = form.Login,
                Password = form.Password, // null = 不变
                Version = form.Version,
            });
            // 登录名和显示名在令牌中:我们签发
            // 新令牌,否则导航栏会一直显示旧名称
            authService.SetToken(Response, client.User);
            Flash.Put(HttpContext, FlashType.Success, "MY_ACCOUNT.UPDATED");
            return Redirect("/my-area");
        }
        catch (BusinessException e)
        {
            return Show(values, null, e.Key, Validation.BusinessErrorFields.GetValueOrDefault(e.Key));
        }
    }

    // -----------------------------------------------------------------------
    // POST /my-account/delete 字段:deletePassword
    // 账户、客户及其所有预约会一并消失,
    // 然后患者被退出登录。
    // -----------------------------------------------------------------------
    [HttpPost("my-account/delete")]
    public async Task<IActionResult> DeleteAccount([FromForm] string? deletePassword)
    {
        var patient = await Patient.ConnectedPatientAsync(application, User);
        var passwordError = await CheckCurrentPasswordAsync(patient, deletePassword);
        if (passwordError is not null)
        {
            var (key, messageParams) = passwordError.Value;
            Flash.Put(HttpContext, FlashType.Danger, key, messageParams);
            return Redirect("/my-account");
        }
        await application.DeleteClientAsync(patient.Id);
        AuthService.ClearToken(Response);
        Flash.Put(HttpContext, FlashType.Success, "MY_ACCOUNT.DELETED");
        return Redirect("/login");
    }

    // 私有方法

    // 若当前密码正确则为 null;否则为消息的键
    // (及其参数)。返回类型是可空的"元组"。
    private async Task<(string Key, Dictionary<string, string>? Params)?> CheckCurrentPasswordAsync(
        Client patient, string? password)
    {
        var ip = AuthController.IpAddress(HttpContext);
        var login = patient.User.Login;
        var minutes = limiter.LoginBlockMinutes(ip, login);
        if (minutes > 0)
        {
            return ("ERRORS.TOO_MANY_ATTEMPTS", new Dictionary<string, string> { ["minutes"] = minutes.ToString() });
        }
        var ok = !string.IsNullOrEmpty(password) && await authService.ValidateUserAsync(login, password) is not null;
        if (!ok)
        {
            limiter.LoginFailure(ip, login);
            return ("ERRORS.WRONG_CURRENT_PASSWORD", null);
        }
        return null;
    }

    private ViewResult Show(
        PersonValues values,
        Dictionary<string, string>? errors = null,
        string? error = null,
        IEnumerable<string>? otherFields = null,
        IReadOnlyDictionary<string, string>? errorParams = null) =>
        View("Account", Validation.Prepare(
            new MyAccountModel { PageTitle = "MY_ACCOUNT.TITLE", Values = values },
            errors, error, otherFields, errorParams));
}

我们来逐段分析这段代码:

  • 第 14–17 行:该控制器的黄金法则:所涉及的患者始终是与令牌关联的那一位,绝不是浏览器发送的标识符;
  • 第 35–39 行:仅限患者。该控制器没有 [[Route]] 特性:每个操作各自提供其完整地址,因为它们没有共同的前缀([/my-area], [/my-account]);
  • 第 44–59 行:“我的区域”页面。[Patient.ConnectedPatientAsync] 根据令牌识别用户;如果其账户在登录后已被删除,则会触发 [InvalidSessionException],由 [Web/HtmlExceptionFilter.cs] 过滤器将其重定向回登录页面。日期由 [WebDates.FormatDay] 根据请求的语言(由本地化中间件设置,参见示例 22)进行格式化;每个预约都包含指向医生当天日程的链接;
  • 第 66–82 行:取消患者的预约。[condition ? value1 : value2] 在这里返回该预约,如果 ID 无效则返回 [null]。不存在的预约和属于其他患者的预约(第 73 行)得到相同的响应:不会泄露任何关于其他患者预约的信息;
  • 第 88–98 行:账户表单,已预填,带有版本号(乐观锁);
  • 第 105–106 行:修改过程,分三步:验证、检查当前密码、业务逻辑;
  • 第 109–115 行:出错时要重新显示的值,绝不包括密码;
  • 第 118–125 行:输入错误。新密码是可选的(留空:保持不变);只有在输入了确认密码时才会对其进行比较;
  • 第 129–138 行:当前密码。[var (key, messageParams) = ...] 解构验证所返回的一对值。错误的密码显示在其字段下方和页面底部;锁定(尝试次数过多)只显示在页面底部,并附带分钟数;
  • 第 143–150 行:由业务层执行修改,它适用与 ADMIN 相同的规则(唯一性、乐观锁);
  • 第 154 行:令牌包含登录名和显示名称:修改之后会签发新的令牌;否则导航栏会保留旧名称;
  • 第 158–160 行:业务层的拒绝会重新显示表单,相关字段以红色高亮;
  • 第 169–183 行:删除账户,同样需要当前密码。错误会通过账户页面上的弹出消息指示(PRG);
  • 第 180–181 行:删除记录、账户和所有预约(ADMIN 所用的业务层方法),随后退出登录:清除令牌 Cookie;
  • 第 190–191 行:验证当前密码。如果密码正确,则返回 [null] ;否则返回一个元组:一对命名值(消息键及其参数)。末尾的 [?] 使这个元组“可为 null”;
  • 第 195–198 行:当前密码与登录使用同一个限制器(参见示例 27)。找到一个仍处于打开状态的会话的人,将无法修改密码、删除账户,也无法无限次地尝试密码;
  • 第 200–204 行:身份验证过程本身,由 [AuthService] 处理;失败的身份验证尝试计为一次失败的登录尝试;
  • 第 209–217 行:账户表单。

11.16.8. Controllers/ErrorController.cs

// =========================================================================
// Controllers/ErrorController.cs
// -------------------------------------------------------------------------
// 错误页面(400、403、404、500)。
//
// 它绝不会通过链接到达:而是中间件
// UseStatusCodePagesWithReExecute("/error/{0}") 和
// UseExceptionHandler("/error/500")(见 Program.cs)用该地址重新执行
// 失败的请求,以构建要返回的页面,
// 取代空响应或异常。
//
// [Route] 而不带 [HttpGet]:该操作接受所有 HTTP 方法,重新
// 执行的请求保留其原始方法(被拒绝的 POST 仍是 POST)。
// =========================================================================

using Microsoft.AspNetCore.Mvc;
using RdvMedecins.Models;

namespace RdvMedecins.Controllers;

public class ErrorController : Controller
{
    private static readonly Dictionary<int, string> Messages = new()
    {
        [StatusCodes.Status400BadRequest] = "ERRORS.BAD_REQUEST",
        [StatusCodes.Status403Forbidden] = "ERRORS.FORBIDDEN",
        [StatusCodes.Status404NotFound] = "ERRORS.NOT_FOUND",
    };

    [Route("error/{code:int}")]
    public IActionResult Show(int code)
    {
        // 页面保留原始错误码(404 仍是 404……);意外的
        // 错误码会变成 500 错误
        if (code < 400 || code > 599)
        {
            code = StatusCodes.Status500InternalServerError;
        }
        Response.StatusCode = code;
        return View("Error", new ErrorModel
        {
            PageTitle = "ERROR_PAGE.TITLE",
            Code = code,
            Message = Messages.GetValueOrDefault(code, "ERRORS.SERVER_ERROR"),
        });
    }
}

这是示例 24 中的控制器,消息已翻译:

  • 第 23–28 行:每个错误代码的消息键。[static readonly]:只有一个字典,在类加载时创建,且从不被替换;
  • 第 30–31 行:缺少 HTTP 方法的 [[Route]] 接受所有方法:重新执行的 POST 请求(例如,患者尝试执行仅限管理员的取消操作)仍然是 POST 请求;
  • 第 35–37 行:非错误的 HTTP 代码(手动输入的 [/error/200] 地址)会变成 500 错误;
  • 第 39 行:页面保留原始的错误代码;
  • 第 40–44 行:页面模板。[GetValueOrDefault] 返回与该代码关联的键,对任何其他代码(尤其是 500)则返回 [ERRORS.SERVER_ERROR]。

11.17. 视图

视图几乎无需做任何决定:它们的模板已由控制器在 [Models/ViewModels.cs] 文件的类中准备好(显示哪些按钮、哪些 URL 元素、哪些翻译键)。每个视图都声明其模板的类型([@model],参见示例 13):[@Model.Xxx] 中的拼写错误会导致编译错误。每个视图还以 [Razor] [@* ... *@] 注释开头,描述其作用;这些注释不会出现在发送给浏览器的页面中。

与第 4 章的示例有一点不同:本案例研究不使用 Tag Helper。分部视图通过 [@await Html.PartialAsync("_Name")] 插入,它等价于示例 15 中的 [<partial name="_Name">] 标记。第二个可选参数提供分部视图的模型;如果省略,分部视图会接收页面的模型。该方法是异步的(分部视图可能需要编译或从磁盘读取):[await] 等待其结果。

11.17.1. 模板与分部视图

11.17.1.1. Views/_ViewImports.cshtml

@* =========================================================================
   Views/_ViewImports.cshtml
   -------------------------------------------------------------------------
   Read before EACH view of this folder and its subfolders: the common
   "using"s, and the parent class of all the views (Web/ViewPage.cs), which
   brings them @T("KEY"), CurrentUser, FlashMessage...
   TModel designates the type of the model of each view (@model ...).
   ========================================================================= *@
@using RdvMedecins
@using RdvMedecins.Models
@using RdvMedecins.Web
@inherits RdvMedecins.Web.ViewPage<TModel>
  • 第 9–11 行:视图所使用类型的命名空间:视图模板([RdvMedecins.Models])、闪存消息([RdvMedecins.Web]);
  • 第 12 行:所有视图的父类 [Web/ViewPage.cs],与示例 22 中相同。它为视图提供翻译 [@T("KEY")]、语言 [Language]、已登录用户 [CurrentUser]、闪存消息 [FlashMessage]、所请求的路径 [CurrentPath],以及方法 [Active] (导航栏中当前活动的菜单项)。在 [NestJS] 版本中,这些信息是通过 [res.locals] 传递的。这里没有 [@addTagHelper] 指令:应用程序不使用 Tag Helper。

11.17.1.2. Views/_ViewStart.cshtml

@* =========================================================================
   Views/_ViewStart.cshtml
   -------------------------------------------------------------------------
   Executed before each view: all the pages use the common layout
   Views/Shared/_Layout.cshtml (hbs did it automatically for
   views/layout.hbs; here, we say it explicitly).
   ========================================================================= *@
@{
    Layout = "_Layout";
}
  • 第 9 行:所有页面都使用 [Views/Shared/_Layout.cshtml] 模板(参见示例 15)。[Handlebars] 会自动使用 [views/layout.hbs];[Razor] 则要求明确指定这一点。

11.17.1.3. Views/Shared/_Layout.cshtml

@* =========================================================================
   Views/Shared/_Layout.cshtml
   -------------------------------------------------------------------------
   The layout COMMON to all the pages. The page requested by the controller
   (Schedule.cshtml, Login.cshtml...) is inserted at the location
   @RenderBody().

   Razor ESCAPES everything it displays with @ (the characters < > & " '
   become &lt; &gt;...): protection against HTML injection through a
   typed name, for example. To insert HTML as is, it must be requested
   explicitly (@Html.Raw, see _Captcha.cshtml).

   Messages: a success is displayed at the TOP of the page (_Flash), an error at the
   BOTTOM, on a light pink background (_Errors).

   The layout shares the model of the page: if it is a ViewModel (see
   Models/ViewModels.cs), we read the title and the error of the page from it.
   ========================================================================= *@
@{
    var page = ViewData.Model as ViewModel;
}
<!doctype html>
<html lang="@Language">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>@T(page?.PageTitle ?? "APP.TITLE") - @T("APP.TITLE")</title>
  <link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="/css/styles.css">
</head>
<body>
  <div class="container py-4">
    @await Html.PartialAsync("_Navbar")
    @await Html.PartialAsync("_Flash")
    @RenderBody()
    @await Html.PartialAsync("_Errors")
  </div>
  @* the "Are you sure?" dialog, hidden as long as it is not needed *@
  @await Html.PartialAsync("_Confirmation")
  <script src="/js/app.js"></script>
</body>
</html>
  • 第 20 行:该模板共享页面模型,可通过 [ViewData.Model] 访问(类型为 [object])。所有页面模板都派生自抽象类 [ViewModel],它包含标题键([PageTitle])和页面错误([Error])。如果模板不是 [as ViewModel] ,则返回 [null] ;[ViewModel]:该模板适用于任何页面;
  • 第 23 行:页面的语言(参见示例 22);
  • 第 27 行:翻译后的标题,例如“Schedule - RdvMedecins”。与示例 22 不同,该键不是由视图在 [ViewData] 中设置的:它由控制器在类型化模型中提供。[page?.PageTitle] 在 [page] 为 [null] 时等于 [null],随后运算符 [??] 会把键替换为 [APP.TITLE];
  • 第 28–29 行:样式表,由 [UseStaticFiles] 从 [wwwroot] 文件夹提供:[Bootstrap] ([wwwroot/lib/bootstrap])以及应用程序专用的样式表;
  • 第 33–36 行:导航栏、成功消息(在顶部)、所请求的页面([@RenderBody()])和错误区域(在底部);
  • 第 39–40 行:确认窗口(隐藏)及其脚本(参见示例 21),加载在页面底部。

11.17.1.4. Views/Shared/_Navbar.cshtml

@* =========================================================================
   Views/Shared/_Navbar.cshtml - the navigation bar.

   Title, FR/EN, role, name, logout - and a menu whose entries
   depend on the role: "Doctors" and "Patients" appear only for
   the ADMIN. It is only a display convenience: the real protection is
   the [Authorize(Roles = ...)] of the controllers (a USER who types /doctors
   by hand gets a 403 page). A patient (USER) also has their
   "My area" menu.
   ========================================================================= *@
@{
    var user = CurrentUser;
}
<nav class="navbar navbar-expand-sm navbar-dark bg-primary rounded mb-4 px-3">
  <span class="navbar-brand mb-0">@T("APP.TITLE")</span>

  @if (user is not null)
  {
    <ul class="navbar-nav me-auto">
      @if (user.IsPatient)
      {
        <li class="nav-item"><a class="nav-link @Active("/my-")" href="/my-area">@T("APP.MENU_MY_AREA")</a></li>
      }
      <li class="nav-item"><a class="nav-link @Active("/schedule")" href="/schedule">@T("APP.MENU_SCHEDULE")</a></li>
      @if (user.IsAdmin)
      {
        <li class="nav-item"><a class="nav-link @Active("/doctors")" href="/doctors">@T("APP.MENU_DOCTORS")</a></li>
        <li class="nav-item"><a class="nav-link @Active("/clients")" href="/clients">@T("APP.MENU_PATIENTS")</a></li>
      }
    </ul>
  }
  else
  {
    <div class="me-auto"></div>
  }

  <div class="d-flex align-items-center gap-2">
    @* FR / EN: simple links (GET /language/fr), the active language highlighted *@
    <div class="btn-group btn-group-sm" role="group" aria-label="FR / EN">
      <a class="btn @(Language == "fr" ? "btn-light" : "btn-outline-light")" href="/language/fr">FR</a>
      <a class="btn @(Language == "en" ? "btn-light" : "btn-outline-light")" href="/language/en">EN</a>
    </div>

    @if (user is not null)
    {
      <span class="badge text-bg-light text-primary">@user.Role</span>
      <span class="text-white">@user.Name</span>
      @* logout is a POST: a form reduced to its button *@
      <form method="post" action="/logout" class="m-0">
        <button type="submit" class="btn btn-sm btn-outline-light">@T("APP.LOGOUT")</button>
      </form>
    }
  </div>
</nav>
  • 第 12 行:已登录的用户,由 [ViewUser] 类(位于 [Web/ViewPage.cs] 中)描述(登录名、姓名、角色、[IsAdmin], [IsPatient]),由 JWT 令牌派生。在公共页面(登录、创建账户)上它被设置为 [null] ;
  • 第 17–31 行:菜单取决于角色:患者看到“我的区域”,ADMIN 看到“医生”和“患者”。这只是为了方便:安全由控制器的 [[Authorize(Roles = ...)]] 特性保证(手动输入 [/doctors] 的患者会收到 403 页面)。[Active("/doctors")] 在所请求的路径以 [active] 开头时返回 [/doctors]:[Bootstrap] 随后高亮该菜单。前缀 [/my-] 涵盖两个患者页面,即 [/my-area] 和 [/my-account];
  • 第 34 行:没有菜单时,由一个空块取而代之([me-auto]:自动右边距),使其余内容保持在导航栏的右侧;
  • 第 40–41 行:示例 22 中的 FR / EN 链接。表达式 [@( ... )] 用括号括起来,因为其中包含空格(参见示例 14);
  • 第 44–52 行:角色、姓名和退出登录按钮,位于 POST 表单中(参见示例 21)。

11.17.1.5. Views/Shared/_Flash.cshtml

@* =========================================================================
   Views/Shared/_Flash.cshtml - the SUCCESS message put by the previous
   action (appointment saved, doctor added...), displayed only
   once, at the top of the page (see Web/Flash.cs).
   An ERROR flash message, for its part, is displayed at the bottom of the page, by
   _Errors.cshtml.
   ========================================================================= *@
@{
    var flash = FlashMessage;
}
@if (flash is { Type: FlashType.Success })
{
  <div class="alert alert-success" role="status">
    @T(flash.Key, flash.Params)
  </div>
}
  • 第 9 行:上一个操作发出的闪存消息(参见示例 20 和 [Web/Flash.cs])。读取闪存消息会将其清除;由于页面读取它两次(在这里和在 [_Errors.cshtml] 中),[Flash] 类在读取后会把它存储在 [HttpContext.Items] 中(参见第 6 章);
  • 第 11 行:[flash is { Type: FlashType.Success }] 是一个属性模式:当 [flash] 不是 [null] 并且其属性 [Type] 等于 [FlashType.Success] 时,条件为真。这里只显示成功消息;
  • 第 14 行:消息是一个键;其可能的参数([name]、[login]、[minutes])是一个字典,传给 [T] 方法的第二种形式。[role="status"]:屏幕阅读器会在不打断用户的情况下播报该消息。

11.17.1.6. Views/Shared/_Errors.cshtml

@* =========================================================================
   Views/Shared/_Errors.cshtml - the error zone, at the BOTTOM of each page,
   on a light pink background (.error-zone class, see wwwroot/css/styles.css).

   It gathers the two possible sources of error:
     - Error: the error of the displayed page (refused form, login or
       first + last name already used, invalid date, incorrect password...);
     - an error flash message, put by the previous action before a
       redirection (slot already booked, deletion refused...).

   role="alert": a screen reader announces the message as soon as the
   page is displayed, even if it is at the bottom.
   ========================================================================= *@
@{
    var page = ViewData.Model as ViewModel;
    var error = page?.Error;
    var flash = FlashMessage;
    var flashError = flash is { Type: FlashType.Danger } ? flash : null;
}
@if (error is not null || flashError is not null)
{
  <div class="error-zone" role="alert">
    @if (error is not null)
    {
      <div>@T(error, page!.ErrorParams)</div>
    }
    @if (flashError is not null)
    {
      <div>@T(flashError.Key, flashError.Params)</div>
    }
  </div>
}
  • 第 15–18 行:错误的两个来源:所显示页面上的错误(模板的 [Error] 属性:表单被拒绝、密码错误等),以及在重定向之前显示的闪存错误消息(时间段已被预约、删除被拒绝等);
  • 第 20–22 行:只要存在其中任何一个,就会显示该区域。[role="alert"]:屏幕阅读器在页面显示后会立即播报该消息,即使它位于底部。类 [error-zone] 定义在 [wwwroot/css/styles.css] 中;
  • 第 25 行:运算符 [!] 告知编译器 [page] 不是 [null]:编译器自己无法推断出这一点,尽管它是确定的,因为从 [error] 读取的 [page] 不是 null。

11.17.1.7. Views/Shared/_Confirmation.cshtml

@* =========================================================================
   Views/Shared/_Confirmation.cshtml - the "Are you sure?" modal dialog.

   It replaces the window.confirm() box of the browser, which can neither be
   styled, nor translated (its buttons stay in the language of the
   browser, not in that of the page).

   A SINGLE dialog for the whole page, hidden (d-none) at first. Its
   labels are translated here, by the server, like the rest of the page;
   the small wwwroot/js/app.js script merely displays it, puts in it
   the message specific to the form (data-confirmation attribute), and sends
   the form if the user confirms.

   Same Bootstrap classes as the booking dialog (Schedule/_Booking.cshtml).
   ========================================================================= *@
<div id="confirmation-modal" class="d-none">
  <div class="modal-backdrop fade show"></div>
  <div class="modal fade show d-block" tabindex="-1" role="alertdialog" aria-modal="true"
       aria-labelledby="confirmation-modal-title" aria-describedby="confirmation-modal-message">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="confirmation-modal-title">@T("CONFIRMATION.TITLE")</h5>
          <button type="button" class="btn-close" data-action="no" aria-label="@T("BOOKING_DIALOG.CLOSE_ARIA")"></button>
        </div>
        <div class="modal-body">
          <p class="mb-0" id="confirmation-modal-message"></p>
        </div>
        <div class="modal-footer">
          @* "No, go back" rather than "Cancel": the question is sometimes
             "Cancel this appointment?", and a "Cancel" button would be ambiguous there *@
          <button type="button" class="btn btn-secondary" data-action="no">@T("CONFIRMATION.NO")</button>
          <button type="button" class="btn btn-danger" data-action="yes">@T("CONFIRMATION.YES")</button>
        </div>
      </div>
    </div>
  </div>
</div>

示例 21 中的窗口,其标签由服务器翻译——与页面其余部分一样——并带有无障碍属性:

  • 第 16 行:整个页面只有一个窗口,初始时隐藏([d-none]);
  • 第 18–19 行:[role="alertdialog"] 表示等待响应的窗口;[aria-modal="true"] 表示页面的其余部分处于非活动状态;[aria-labelledby] 和 [aria-describedby] 指定屏幕阅读器朗读的标题和消息;
  • 第 24 行:关闭按钮,表示“否”([data-action="no"])。它没有文本:[aria-label] 为屏幕阅读器提供名称;
  • 第 32–33 行:用“否,返回”而不是“取消”:有时问题是“取消此预约?”,在这种情况下“取消”按钮会有歧义。

11.17.1.8. Views/Auth/_Captcha.cshtml

@* =========================================================================
   Views/Auth/_Captcha.cshtml - the captcha of the authentication page
   (see Auth/CaptchaService.cs). It protects both the login and
   the access to account creation ("Create a patient account" button).

   @Html.Raw(...): the SVG image is inserted AS IS in the page, without
   escaping. It is harmless here because this SVG is built by the
   server itself and contains nothing that comes from the user - we would
   NEVER do this with user input.

   The hidden captchaId field tells the server WHICH captcha to check; the right
   answer, for its part, is never sent to the browser.
   "Another image" simply reloads the page (path = the current URL).
   ========================================================================= *@
@model RdvMedecins.Auth.Captcha
<div class="mb-3">
  <label class="form-label" for="captcha">@T("CAPTCHA.LABEL")</label>
  <div class="d-flex align-items-center gap-3 mb-2">
    <div class="captcha-image" role="img" aria-label="@T("CAPTCHA.IMAGE_ALT")">@Html.Raw(Model.Svg)</div>
    <a class="small" href="@CurrentPath">@T("CAPTCHA.NEW_IMAGE")</a>
  </div>
  <input type="hidden" name="captchaId" value="@Model.Id">
  <input id="captcha" name="captcha" type="text" maxlength="10" autocomplete="off" autocapitalize="off" spellcheck="false" required
         class="form-control">
  <div class="form-text">@T("CAPTCHA.HELP")</div>
</div>
  • 第 15 行:该分部视图有自己的模板,即由 [Auth/CaptchaService.cs] 生成的验证码(CAPTCHA)(参见示例 27):其 ID 和图像;
  • 第 19 行:SVG 图像原样插入(参见示例 14):它由服务器生成,不含用户的任何输入。[role="img"] 和 [aria-label] 使屏幕阅读器把它当作图像;
  • 第 20 行:“换一张图片”只是重新加载当前页面:会生成新的验证码(CAPTCHA);
  • 第 22 行:验证码 ID,位于隐藏字段中:它告诉服务器要验证哪个验证码。而正确答案则绝不会离开服务器;
  • 第 23–24 行:输入框。[autocomplete="off"]、[autocapitalize="off"] 和 [spellcheck="false"] 可防止浏览器对抄写的字符进行建议、自动大写或纠正。

11.17.1.9. Views/Shared/_PersonFields.cshtml

@* =========================================================================
   Views/Shared/_PersonFields.cshtml - the identity fields (title,
   first name, last name), common to three forms: the ADMIN's doctor/client form,
   "Create a patient account" and "Manage my account".
   The partial receives the model of the page that inserts it (a FormView):
   values, message under each field, fields outlined in red.

   selected="@selected": a boolean attribute. Razor writes selected="selected"
   if the value is true, and OMITS the attribute if it is false.
   ========================================================================= *@
@model FormView
<div class="mb-3">
  <label class="form-label" for="title">@T("PERSONS.TITLE_LABEL")</label>
  <select id="title" name="title" class="form-select @Model.InvalidClass("title")">
    @foreach (var (value, selected) in Model.Titles)
    {
      <option value="@value" selected="@selected">@value</option>
    }
  </select>
  @if (Model.ErrorOf("title") is { } titleError)
  {
    <div class="invalid-feedback">@T(titleError)</div>
  }
</div>

<div class="row g-3 mb-3">
  <div class="col-sm-6">
    <label class="form-label" for="firstName">@T("PERSONS.FIRSTNAME_LABEL")</label>
    <input id="firstName" name="firstName" type="text" maxlength="20" required
           class="form-control @Model.InvalidClass("firstName")" value="@Model.Values.FirstName">
    @if (Model.ErrorOf("firstName") is { } firstNameError)
    {
      <div class="invalid-feedback">@T(firstNameError)</div>
    }
  </div>
  <div class="col-sm-6">
    <label class="form-label" for="lastName">@T("PERSONS.LASTNAME_LABEL")</label>
    <input id="lastName" name="lastName" type="text" maxlength="20" required
           class="form-control @Model.InvalidClass("lastName")" value="@Model.Values.LastName">
    @if (Model.ErrorOf("lastName") is { } lastNameError)
    {
      <div class="invalid-feedback">@T(lastNameError)</div>
    }
  </div>
</div>

身份字段(称谓、名、姓),三个表单共用:ADMIN 的医生或客户表单、账户创建表单和患者账户管理表单。

  • 第 11 行:[FormView] 是这三个表单模板的(抽象)父类。它包含已输入的值([Values])、每个被拒绝字段的错误消息([Errors])以及要以红色高亮的字段([InvalidFields])。因此该分部视图可以接受这三个页面中每一个的模板;
  • 第 14–19 行:称谓列表。[Model.Titles] 返回元组(值,是否选中);[var (value, selected)] 把每个元组分解为两个变量。[selected="@selected"] 是布尔属性,仅当值为 true 时才会写出(参见示例 17)。[InvalidClass("title")] 在字段要以红框标出时返回 [is-invalid] (参见示例 19);
  • 第 20–23 行:字段的错误消息(如果有)。[ErrorOf] 返回该消息,或 [null];条件 [is { } titleError] 在值不是 [null] 时为真,然后把它存储在新变量 [titleError] 中;
  • 第 26–45 行:名和姓,格式相同,在足够宽的屏幕上并排显示([Bootstrap] 网格:[col-sm-6])。属性 [maxlength] 和 [required] 只是为了方便:插入此分部视图的表单带有属性 [novalidate],验证由服务器处理。

11.17.1.10. Views/Schedule/_Booking.cshtml

@* =========================================================================
   Views/Schedule/_Booking.cshtml - the booking dialog.

   Same technique as the Angular client (booking-dialog): the REAL Bootstrap
   classes of a modal dialog (.modal, .modal-backdrop...), made
   visible "hard-coded" (show d-block) rather than by the JavaScript of
   Bootstrap. The difference: it is the SERVER that decides to display it
   (&book=... parameter of the URL), and closing it amounts to following a link
   to the same page without this parameter.
   ========================================================================= *@
@model ScheduleModel
@{
    var booking = Model.Booking!;
}
<div class="modal-backdrop fade show"></div>
<div class="modal fade show d-block" tabindex="-1" role="dialog" aria-modal="true" aria-labelledby="booking-title">
  <div class="modal-dialog modal-dialog-centered">
    <form method="post" action="/schedule/book" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="booking-title">@T("BOOKING_DIALOG.TITLE")</h5>
        <a class="btn-close" href="@Model.BackUrl" aria-label="@T("BOOKING_DIALOG.CLOSE_ARIA")"></a>
      </div>

      <div class="modal-body">
        <p>@T("BOOKING_DIALOG.SLOT", ("time", booking.Time))</p>

        @* what the server needs to know in addition to the chosen patient *@
        <input type="hidden" name="doctorId" value="@Model.DoctorId">
        <input type="hidden" name="day" value="@Model.Day">
        <input type="hidden" name="slotId" value="@booking.SlotId">

        @if (booking.Patient is not null)
        {
          @* a patient books for themselves: no list to choose from
             (and the server ignores any clientId anyway) *@
          <p class="mb-0">@T("BOOKING_DIALOG.PATIENT_LABEL"): <strong>@booking.Patient</strong></p>
        }
        else
        {
          <label class="form-label" for="clientId">@T("BOOKING_DIALOG.PATIENT_LABEL")</label>
          <select id="clientId" name="clientId" class="form-select" required autofocus>
            <option value="">@T("BOOKING_DIALOG.CHOOSE_PATIENT")</option>
            @foreach (var client in booking.Clients)
            {
              <option value="@client.Id">@client.Label</option>
            }
          </select>
        }
      </div>

      <div class="modal-footer">
        <a class="btn btn-secondary" href="@Model.BackUrl">@T("BOOKING_DIALOG.CANCEL")</a>
        <button type="submit" class="btn btn-primary">@T("BOOKING_DIALOG.CONFIRM")</button>
      </div>
    </form>
  </div>
</div>
  • 第 11 行:该分部视图接收日历页面的模板。[Model.Booking!]:只有当 [Booking] 不是 [null] 时,页面才会插入它,运算符 [!] 向编译器断言了这一点;
  • 第 15–16 行:模态窗口及其灰色背景所用的 [Bootstrap] 类,被“硬编码”为可见([show d-block]):当 URL 包含参数 [book] 时,服务器决定显示该窗口。[Bootstrap] 的 [JavaScript] 并未被使用(甚至没有加载);
  • 第 18 行:窗口的内容就是预约表单本身;
  • 第 21 行:关闭窗口会跳转到同一日历的链接,不带 [book] 参数([BackUrl],由控制器准备);
  • 第 25 行:“时间段 8:00 - 8:20”:一个翻译参数;
  • 第 28–30 行:隐藏字段:除所选患者之外,服务器还需要的附加信息;
  • 第 32–48 行:患者看到自己的姓名;管理者(ADMIN、DOCTOR)从列表中选择患者。第一个选项的值为空:配合 [required],浏览器要求必须选择一位真正的患者。[autofocus] 把光标放在列表中;
  • 第 52–53 行:“取消”是一个链接,X 也是;“确认”提交表单。

11.17.2. 页面

11.17.2.1. Views/Auth/Login.cshtml

@* =========================================================================
   Views/Auth/Login.cshtml - the login form.
   An ordinary HTML <form>: the browser itself sends login,
   password and captcha answer with POST /login, without JavaScript. On
   failure, the server sends back THIS page, with the login already typed, a
   NEW captcha and the error, displayed at the bottom of the page by the layout.

   @model: the type of the view model. The compiler checks each
   @Model.Xxx (a typo is a compilation error).
   ========================================================================= *@
@model LoginModel
@{
    var loginTyped = Model.Login != "";
}
<div class="row justify-content-center">
  <div class="col-sm-8 col-md-6 col-lg-5">
    <div class="card p-4">
      <h5 class="card-title mb-3">@T("LOGIN.TITLE")</h5>

      <form method="post" action="/login">
        <div class="mb-3">
          <label class="form-label" for="login">@T("LOGIN.LOGIN_LABEL")</label>
          <input id="login" name="login" type="text" class="form-control" autocomplete="username"
                 value="@Model.Login" required autofocus="@(!loginTyped)">
        </div>
        <div class="mb-3">
          <label class="form-label" for="password">@T("LOGIN.PASSWORD_LABEL")</label>
          <input id="password" name="password" type="password" class="form-control"
                 autocomplete="current-password" required autofocus="@loginTyped">
        </div>

        @await Html.PartialAsync("_Captcha", Model.Captcha)

        <button type="submit" class="btn btn-primary w-100">@T("LOGIN.SUBMIT")</button>

        @* no account yet: a patient can create one themselves.
           It is NOT a simple link: it is a second submit button of
           THIS form, which goes to another address (formaction). The
           server checks the captcha above there before opening the account
           creation page (see RegistrationController).
           formnovalidate: the browser does not require login and password
           (useless to create an account); it is the server that checks
           the captcha. Enter in a field always triggers the FIRST
           button of the form, "Log in". *@
        <button type="submit" class="btn btn-outline-primary w-100 mt-3"
                formaction="/register/access" formnovalidate>@T("LOGIN.CREATE_ACCOUNT")</button>
        <div class="form-text text-center">@T("LOGIN.CREATE_ACCOUNT_HELP")</div>
      </form>

      <div class="text-muted small mt-3">
        @T("LOGIN.DEMO_ACCOUNTS")
        <ul class="mb-0 mt-1">
          <li><code>admin</code> - @T("LOGIN.DEMO_ADMIN")</li>
          <li><code>pelissier</code>, <code>tatou</code>, <code>dupont</code> - @T("LOGIN.DEMO_DOCTOR")</li>
          <li><code>martin</code>, <code>durand</code>, <code>bistrou</code>, <code>german</code> - @T("LOGIN.DEMO_USER")</li>
        </ul>
      </div>
    </div>
  </div>
</div>
  • 第 13 行:失败之后,控制器返回此页面,并带有已输入的用户名;
  • 第 20 行:标准的 HTML 表单:浏览器自行提交用户名、密码和验证码(CAPTCHA)答案;
  • 第 23–29 行:[autofocus] 是布尔属性:两个字段中只有一个会带有它。光标放在用户名字段中;如果已经知道用户名,则放在密码字段中。[autocomplete] 的值([username]、[current-password])有助于浏览器的密码管理器;
  • 第 32 行:验证码(CAPTCHA);第二个参数提供分部视图的模板;
  • 第 45–46 行:第二个按钮把同一个表单提交到 [/register/access] (特性 [formaction],参见示例 20):服务器在那里验证验证码(CAPTCHA),然后才打开创建账户页面。[formnovalidate]:浏览器不要求填写用户名和密码,因为创建账户并不需要它们。在字段中按 Enter 键总是会触发表单上的第一个按钮:“登录”;
  • 第 51–56 行:演示账户(密码 = 用户名)。

11.17.2.2. Views/Schedule/Schedule.cshtml

@* =========================================================================
   Views/Schedule/Schedule.cshtml - the main page (see ScheduleController).
   Three blocks, like the three components of the Angular client:
     1. the choice of the doctor and the day  (<app-doctor-day-picker>)
     2. the schedule                          (<app-agenda>)
     3. the booking dialog                    (<app-booking-dialog>)
   A possible error (invalid date, unknown doctor) is displayed at the
   bottom of the page by the layout (see Views/Shared/_Errors.cshtml).
   ========================================================================= *@
@model ScheduleModel

@* 1. choice of the doctor and the day: a GET form, which simply
   reloads this page with ?doctorId=...&day=... in the URL *@
<form method="get" action="/schedule" class="card p-3 mb-3">
  <div class="row g-2 align-items-end">
    <div class="col-sm-5">
      <label class="form-label" for="doctorId">@T("DOCTOR_DAY_PICKER.DOCTOR_LABEL")</label>
      <select id="doctorId" name="doctorId" class="form-select" required>
        <option value="">@T("DOCTOR_DAY_PICKER.CHOOSE_DOCTOR")</option>
        @foreach (var doctor in Model.Doctors)
        {
          <option value="@doctor.Id" selected="@doctor.Selected">@doctor.Label</option>
        }
      </select>
    </div>
    <div class="col-sm-4">
      <label class="form-label" for="day">@T("DOCTOR_DAY_PICKER.DAY_LABEL")</label>
      <input id="day" name="day" type="date" class="form-control" value="@Model.Day" required>
    </div>
    <div class="col-sm-3">
      <button type="submit" class="btn btn-primary w-100">@T("DOCTOR_DAY_PICKER.VIEW_SCHEDULE")</button>
    </div>
  </div>
</form>

@* patient who already has an upcoming appointment: why there is no "Book" button *@
@if (Model.Info is not null)
{
  <div class="alert alert-info">
    @T(Model.Info) <a href="/my-area" class="alert-link">@T("APP.MENU_MY_AREA")</a>
  </div>
}

@* 2. the schedule *@
@if (Model.Schedule is { } schedule)
{
  <div class="card p-3">
    <h5>@T("SCHEDULE.TITLE_PREFIX") @schedule.Day - @schedule.Doctor</h5>

    @if (schedule.Rows.Count > 0)
    {
      <table class="table table-hover align-middle">
        <thead>
          <tr>
            <th>@T("SCHEDULE.COLUMN_SLOT")</th>
            <th>@T("SCHEDULE.COLUMN_STATUS")</th>
            <th></th>
          </tr>
        </thead>
        <tbody>
          @foreach (var row in schedule.Rows)
          {
            <tr class="@(row.Bookable ? "free-slot" : null)">
              <td>@row.Time</td>
              <td>
                @* [Patient] is filled only if the user is allowed to
                   see this name (ADMIN, DOCTOR, or the patient for THEIR
                   appointment) - otherwise, simply "Booked" *@
                @if (row.Free)
                {
                  <span class="badge text-bg-success">@T("SCHEDULE.FREE")</span>
                }
                else if (row.Patient is not null)
                {
                  <span class="badge @(row.Mine ? "text-bg-primary" : "text-bg-secondary")">@row.Patient</span>
                }
                else
                {
                  <span class="badge text-bg-secondary">@T("SCHEDULE.BOOKED_BY_OTHER")</span>
                }
              </td>
              <td>
                @* the displayed buttons have been decided by the controller
                   (Bookable, AppointmentId) according to the role of the user *@
                @if (row.Bookable)
                {
                  @* "Book" is a simple link: it reopens this page
                     with the booking dialog of this slot *@
                  <a class="btn btn-sm btn-outline-success" href="@row.BookUrl">@T("SCHEDULE.BOOK")</a>
                }
                @if (row.AppointmentId is not null)
                {
                  @* "Cancel" MODIFIES data: it is therefore a POST *@
                  <form method="post" action="/schedule/cancel" class="m-0"
                        data-confirmation="@T("SCHEDULE.CANCEL_CONFIRM")">
                    <input type="hidden" name="appointmentId" value="@row.AppointmentId">
                    <input type="hidden" name="doctorId" value="@Model.DoctorId">
                    <input type="hidden" name="day" value="@Model.Day">
                    <button type="submit" class="btn btn-sm btn-outline-danger">@T("SCHEDULE.CANCEL_APPOINTMENT")</button>
                  </form>
                }
              </td>
            </tr>
          }
        </tbody>
      </table>
    }
    else
    {
      <p class="text-muted mb-0">@T("SCHEDULE.NO_SLOTS")</p>
    }
  </div>
}
else
{
  <p class="text-muted">@T("SCHEDULE.EMPTY_STATE")</p>
}

@* 3. the booking dialog, only if the URL contains &book=... *@
@if (Model.Booking is not null)
{
  @await Html.PartialAsync("_Booking", Model)
}

我们来逐段说明这段代码:

  • 第 14–34 行:选择医生和日期:一个 GET 表单(参见示例 17),它会在 URL 中带上 [?doctorId=...&day=...] 重新加载页面。每位医生是一个 [OptionView] ,它指明该医生是否被选中。[type="date"] 字段以 [yyyy-mm-dd] 格式发送日期(参见示例 18);
  • 第 37–42 行:给已有即将到来的预约的患者的消息:它说明了为什么没有“预约”按钮;
  • 第 45 行:日历(如果被请求)。条件 [is { } schedule] 检查该属性不是 [null] ,并把它的值存储在变量 [schedule] 中;
  • 第 48 行:标题:“Schedule for 2026-09-25 – Mme Marie PELISSIER”;
  • 第 63 行:可预约的时间段在鼠标悬停时变色(类 [free-slot],参见 [styles.css])。当属性的值为 [null] 时,[Razor] 根本不会写出该属性:其他行没有 [class] 属性;
  • 第 69–80 行:三种情形:可预约;已预约,并显示患者姓名(如果是已登录患者的预约则显示为蓝色,[Mine]);已预约但看不到姓名,显示“已预约”。只有在用户有权查看该姓名时,控制器才会填充 [Patient] ;
  • 第 85–90 行:“预约”是一个链接:它重新打开此页面,并显示该时间段的预约窗口([BookUrl],由控制器准备);
  • 第 91–101 行:“取消”会修改数据:它是带有确认的 POST 表单([data-confirmation],参见示例 21)。隐藏字段 [doctorId] 和 [day] 使控制器能够重定向到同一日历。在循环中,[Model] 始终指向页面模板:不需要 [@root] 或 [Handlebars] 中的对应物;
  • 第 110 行和第 116 行:没有可用时间段的医生,或者尚未请求任何日历;
  • 第 120–123 行:预约窗口(如果控制器已准备好它)。

11.17.2.3. Views/Persons/List.cshtml

@* =========================================================================
   Views/Persons/List.cshtml - the list of the doctors OR of the clients (ADMIN).
   A single view for both: the labels specific to each one arrive in
   Model.Keys (see DoctorsController / ClientsController).
   ========================================================================= *@
@model PersonListModel
<div class="d-flex justify-content-between align-items-center mb-3">
  <h4 class="mb-0">@T(Model.Keys.Title)</h4>
  <a class="btn btn-primary" href="@Model.AddUrl">@T(Model.Keys.Add)</a>
</div>

<div class="card p-3">
  @if (Model.Persons.Count > 0)
  {
    <table class="table table-hover align-middle mb-0">
      <thead>
        <tr>
          <th>@T("PERSONS.COLUMN_TITLE")</th>
          <th>@T("PERSONS.COLUMN_FIRSTNAME")</th>
          <th>@T("PERSONS.COLUMN_LASTNAME")</th>
          <th>@T("PERSONS.COLUMN_LOGIN")</th>
          <th></th>
        </tr>
      </thead>
      <tbody>
        @foreach (var person in Model.Persons)
        {
          <tr>
            <td>@person.Title</td>
            <td>@person.FirstName</td>
            <td>@person.LastName</td>
            <td><code>@person.Login</code></td>
            <td class="text-end">
              <div class="d-inline-flex gap-2">
                <a class="btn btn-sm btn-outline-primary" href="@person.EditUrl">@T("PERSONS.EDIT")</a>
                @* data-confirmation: a confirmation dialog will open
                   before the form is sent (see wwwroot/js/app.js) *@
                <form method="post" action="@person.DeleteUrl" class="m-0"
                      data-confirmation="@T(Model.Keys.ConfirmDelete)">
                  <button type="submit" class="btn btn-sm btn-outline-danger">@T("PERSONS.DELETE")</button>
                </form>
              </div>
            </td>
          </tr>
        }
      </tbody>
    </table>
  }
  else
  {
    <p class="text-muted mb-0">@T(Model.Keys.Empty)</p>
  }
</div>

医生和客户共用一个视图:

  • 第 8–9 行:每类用户特有的文本以键的形式出现([Model.Keys],类型为 [PersonKeys]),由 [DoctorsController] 或 [ClientsController] 提供:[DOCTORS.TITLE] 或 [CLIENTS.TITLE] 等;
  • 第 26–45 行:每人一行,带有两个按钮;
  • 第 35 行:“编辑”是指向表单的链接;
  • 第 38–41 行:“删除”是带有确认的 POST 表单;
  • 第 51 行:“没有医生。”或“没有患者。”

11.17.2.4. Views/Persons/Form.cshtml

@* =========================================================================
   Views/Persons/Form.cshtml - creation OR update of a doctor
   or of a client (ADMIN). Model.Creating distinguishes the two cases.

   When the input is refused (empty field, login already taken...), the
   controller sends back THIS view with:
     - the values already typed (Model.Values);
     - the faulty fields outlined in red (Bootstrap "is-invalid" class);
     - under a field refused by the validation, its message;
     - the error message of the page, displayed AT THE BOTTOM of the page by the
       layout (see Views/Shared/_Errors.cshtml).
   ========================================================================= *@
@model PersonFormModel
<div class="row justify-content-center">
  <div class="col-md-8 col-lg-6">
    <div class="card p-4">
      <h5 class="card-title mb-3">@T(Model.PageTitle)</h5>

      @* novalidate: we let the SERVER validate (it is the one that has authority);
         the browser checks (required...) are only a convenience,
         which a user can always bypass *@
      <form method="post" action="@Model.Action" novalidate>
        @if (!Model.Creating)
        {
          <input type="hidden" name="version" value="@Model.Values.Version">
        }

        @* title, first name, last name: partial common to three forms *@
        @await Html.PartialAsync("_PersonFields", Model)

        <h6 class="mt-4 text-muted">@T("PERSONS.ACCOUNT_SECTION")</h6>

        <div class="mb-3">
          <label class="form-label" for="login">@T("PERSONS.LOGIN_LABEL")</label>
          <input id="login" name="login" type="text" maxlength="30" autocomplete="off"
                 class="form-control @Model.InvalidClass("login")" value="@Model.Values.Login">
          @if (Model.ErrorOf("login") is { } loginError)
          {
            <div class="invalid-feedback">@T(loginError)</div>
          }
          else
          {
            <div class="form-text">@T(Model.Creating ? "PERSONS.LOGIN_HELP_CREATE" : "PERSONS.LOGIN_HELP_EDIT")</div>
          }
        </div>

        <div class="mb-4">
          <label class="form-label" for="password">@T("PERSONS.PASSWORD_LABEL")</label>
          @* never pre-filled: the password never goes back to the browser *@
          <input id="password" name="password" type="password" maxlength="72" autocomplete="new-password"
                 class="form-control @Model.InvalidClass("password")">
          @if (Model.ErrorOf("password") is { } passwordError)
          {
            <div class="invalid-feedback">@T(passwordError)</div>
          }
          else
          {
            <div class="form-text">@T(Model.Creating ? "PERSONS.PASSWORD_HELP_CREATE" : "PERSONS.PASSWORD_HELP_EDIT")</div>
          }
        </div>

        <div class="d-flex gap-2">
          <button type="submit" class="btn btn-primary">@T("PERSONS.SAVE")</button>
          <a class="btn btn-secondary" href="@Model.ListUrl">@T("PERSONS.BACK")</a>
        </div>
      </form>
    </div>
  </div>
</div>

我们来逐段说明这段代码:

  • 第 17 行:标题(“添加医生”、“编辑患者”等)是页面标题键,由控制器提供;
  • 第 22 行:URL 由控制器提供:同一个视图既用于添加也用于编辑医生和客户。[novalidate]:由服务器处理验证(参见示例 19);
  • 第 23–25 行:对于编辑,记录版本位于隐藏字段中:这就是示例 28 中的乐观锁;
  • 第 29 行:身份字段;
  • 第 34–44 行:登录名,带有错误消息,如果没有错误则带有帮助文本。帮助文本因是添加还是编辑而不同(“可选:默认为小写的姓氏。”);
  • 第 48–59 行:密码,从不预填;它绝不会回传给浏览器。[autocomplete="new-password"]:浏览器不会建议管理员已保存的密码。长度限制为 72 个字符,因为 [bcrypt] 算法会忽略其后的字符;
  • 第 64 行:返回列表的链接是一个超链接。

11.17.2.5. Views/Registration/Registration.cshtml

@* =========================================================================
   Views/Registration/Registration.cshtml - "Create a patient account" (public
   page, see RegistrationController). Same identity fields as the
   ADMIN's form (_PersonFields partial), but the login and the
   password are required, with confirmation.
   No captcha HERE: this page is only reached after copying
   the one of the authentication page ("Create a patient account" button).
   ========================================================================= *@
@model RegistrationModel
<div class="row justify-content-center">
  <div class="col-md-8 col-lg-6">
    <div class="card p-4">
      <h5 class="card-title mb-1">@T("REGISTRATION.TITLE")</h5>
      <p class="text-muted small mb-3">@T("REGISTRATION.INTRO")</p>

      <form method="post" action="/register" novalidate>
        @await Html.PartialAsync("_PersonFields", Model)

        <h6 class="mt-4 text-muted">@T("PERSONS.ACCOUNT_SECTION")</h6>

        <div class="mb-3">
          <label class="form-label" for="login">@T("PERSONS.LOGIN_LABEL")</label>
          <input id="login" name="login" type="text" maxlength="30" autocomplete="username" required
                 class="form-control @Model.InvalidClass("login")" value="@Model.Values.Login">
          @if (Model.ErrorOf("login") is { } loginError)
          {
            <div class="invalid-feedback">@T(loginError)</div>
          }
          else
          {
            <div class="form-text">@T("REGISTRATION.LOGIN_HELP")</div>
          }
        </div>

        <div class="row g-3 mb-3">
          <div class="col-sm-6">
            <label class="form-label" for="password">@T("PERSONS.PASSWORD_LABEL")</label>
            <input id="password" name="password" type="password" maxlength="72" autocomplete="new-password" required
                   class="form-control @Model.InvalidClass("password")">
            @if (Model.ErrorOf("password") is { } passwordError)
            {
              <div class="invalid-feedback">@T(passwordError, ("min", Model.PasswordMin))</div>
            }
            else
            {
              <div class="form-text">@T("REGISTRATION.PASSWORD_HELP", ("min", Model.PasswordMin))</div>
            }
          </div>
          <div class="col-sm-6">
            <label class="form-label" for="confirmation">@T("ACCOUNT.CONFIRMATION_LABEL")</label>
            <input id="confirmation" name="confirmation" type="password" maxlength="72" autocomplete="new-password" required
                   class="form-control @Model.InvalidClass("confirmation")">
            @if (Model.ErrorOf("confirmation") is { } confirmationError)
            {
              <div class="invalid-feedback">@T(confirmationError)</div>
            }
          </div>
        </div>

        <div class="d-flex gap-2">
          <button type="submit" class="btn btn-primary">@T("REGISTRATION.SUBMIT")</button>
          <a class="btn btn-secondary" href="/login">@T("REGISTRATION.BACK_TO_LOGIN")</a>
        </div>
      </form>
    </div>
  </div>
</div>

创建客户账户,公共页面。这里没有验证码(CAPTCHA):只有在登录页面输入了验证码之后才能到达此页面。

  • 第 17 行:与 ADMIN 表单相同的身份字段;
  • 第 22–32 行:用户名,这次是必填的;
  • 第 37–47 行:帮助文本和“太短”消息带有参数 [{min}],即由模板提供的密码最小长度([PasswordMin])。不带参数 [{min}] 的消息会直接忽略所提供的值;
  • 第 50–56 行:确认密码;
  • 第 62 行:返回登录页面。

11.17.2.6. Views/PatientArea/Area.cshtml

@* =========================================================================
   Views/PatientArea/Area.cshtml - "My area": the home page of the
   patient (USER role), displayed right after logging in.
     - two options: [Manage my account] and [View a schedule];
     - their upcoming appointment, if they have one, with the means to cancel it.
   ========================================================================= *@
@model AreaModel
<h4 class="mb-3">@T("AREA.HELLO", ("name", Model.Patient))</h4>

<div class="row g-3 mb-4">
  <div class="col-sm-6">
    <a class="card p-4 h-100 text-decoration-none option-card" href="/my-account">
      <h5 class="mb-1">@T("AREA.MANAGE_ACCOUNT")</h5>
      <span class="text-muted">@T("AREA.MANAGE_ACCOUNT_HELP")</span>
    </a>
  </div>
  <div class="col-sm-6">
    <a class="card p-4 h-100 text-decoration-none option-card" href="/schedule">
      <h5 class="mb-1">@T("AREA.VIEW_SCHEDULE")</h5>
      <span class="text-muted">@T("AREA.VIEW_SCHEDULE_HELP")</span>
    </a>
  </div>
</div>

<div class="card p-3">
  <h5>@T("AREA.MY_APPOINTMENT")</h5>
  @if (Model.Appointments.Count > 0)
  {
    @* normally only one (rule "one upcoming appointment at a time"),
       but the page can display several *@
    for (var i = 0; i < Model.Appointments.Count; i++)
    {
      var appointment = Model.Appointments[i];
      var last = i == Model.Appointments.Count - 1;
      <div class="d-flex flex-wrap justify-content-between align-items-center gap-2 py-2 @(last ? "" : "border-bottom")">
        <div>
          <div class="fw-semibold">@appointment.Day, @appointment.Time</div>
          <div class="text-muted">@appointment.Doctor - <a href="@appointment.ScheduleUrl">@T("AREA.SEE_IN_SCHEDULE")</a></div>
        </div>
        <form method="post" action="/my-area/cancel" class="m-0"
              data-confirmation="@T("SCHEDULE.CANCEL_CONFIRM")">
          <input type="hidden" name="appointmentId" value="@appointment.Id">
          <button type="submit" class="btn btn-outline-danger">@T("AREA.CANCEL_APPOINTMENT")</button>
        </form>
      </div>
    }
  }
  else
  {
    <p class="text-muted mb-0">@T("AREA.NO_APPOINTMENT")</p>
  }
</div>
  • 第 8 行:“Hello Mr Jean MARTIN”;
  • 第 12–21 行:两个选项都是链接,显示为卡片(类 [option-card],参见 [styles.css]);
  • 第 31–46 行:即将到来的预约(通常只有一个)。在 [@if] 块内,格式是 [C#]:[for] 循环不带 [@] 书写。边框([border-bottom])把各个预约隔开,最后一个之后除外;
  • 第 40–44 行:取消,带有确认的 POST 表单。

11.17.2.7. Views/PatientArea/Account.cshtml

@* =========================================================================
   Views/PatientArea/Account.cshtml - "Manage my account" (USER role).
   Two independent forms on the same page:
     1. the update (identity, login, optional new password);
     2. the deletion of the account - which also cancels its appointments.
   Both require the CURRENT password.
   ========================================================================= *@
@model MyAccountModel
<div class="row justify-content-center">
  <div class="col-md-8 col-lg-6">

    @* 1. update *@
    <div class="card p-4 mb-4">
      <h5 class="card-title mb-3">@T("MY_ACCOUNT.TITLE")</h5>

      <form method="post" action="/my-account" novalidate>
        <input type="hidden" name="version" value="@Model.Values.Version">

        @await Html.PartialAsync("_PersonFields", Model)

        <h6 class="mt-4 text-muted">@T("PERSONS.ACCOUNT_SECTION")</h6>

        <div class="mb-3">
          <label class="form-label" for="login">@T("PERSONS.LOGIN_LABEL")</label>
          <input id="login" name="login" type="text" maxlength="30" autocomplete="username" required
                 class="form-control @Model.InvalidClass("login")" value="@Model.Values.Login">
          @if (Model.ErrorOf("login") is { } loginError)
          {
            <div class="invalid-feedback">@T(loginError)</div>
          }
        </div>

        <div class="row g-3 mb-3">
          <div class="col-sm-6">
            <label class="form-label" for="password">@T("MY_ACCOUNT.NEW_PASSWORD_LABEL")</label>
            <input id="password" name="password" type="password" maxlength="72" autocomplete="new-password"
                   class="form-control @Model.InvalidClass("password")">
            @if (Model.ErrorOf("password") is { } passwordError)
            {
              <div class="invalid-feedback">@T(passwordError, ("min", Model.PasswordMin))</div>
            }
            else
            {
              <div class="form-text">@T("PERSONS.PASSWORD_HELP_EDIT")</div>
            }
          </div>
          <div class="col-sm-6">
            <label class="form-label" for="confirmation">@T("ACCOUNT.CONFIRMATION_LABEL")</label>
            <input id="confirmation" name="confirmation" type="password" maxlength="72" autocomplete="new-password"
                   class="form-control @Model.InvalidClass("confirmation")">
            @if (Model.ErrorOf("confirmation") is { } confirmationError)
            {
              <div class="invalid-feedback">@T(confirmationError)</div>
            }
          </div>
        </div>

        <div class="mb-4">
          <label class="form-label" for="currentPassword">@T("MY_ACCOUNT.CURRENT_PASSWORD_LABEL")</label>
          <input id="currentPassword" name="currentPassword" type="password" maxlength="72" autocomplete="current-password" required
                 class="form-control @Model.InvalidClass("currentPassword")">
          @if (Model.ErrorOf("currentPassword") is { } currentError)
          {
            <div class="invalid-feedback">@T(currentError)</div>
          }
          else
          {
            <div class="form-text">@T("MY_ACCOUNT.CURRENT_PASSWORD_HELP")</div>
          }
        </div>

        <div class="d-flex gap-2">
          <button type="submit" class="btn btn-primary">@T("PERSONS.SAVE")</button>
          <a class="btn btn-secondary" href="/my-area">@T("MY_ACCOUNT.BACK")</a>
        </div>
      </form>
    </div>

    @* 2. deletion *@
    <div class="card p-4 border-danger">
      <h5 class="card-title text-danger mb-1">@T("MY_ACCOUNT.DELETE_TITLE")</h5>
      <p class="text-muted small">@T("MY_ACCOUNT.DELETE_HELP")</p>
      <form method="post" action="/my-account/delete" class="d-flex flex-wrap gap-2 align-items-end"
            data-confirmation="@T("MY_ACCOUNT.DELETE_CONFIRM")">
        <div class="flex-grow-1">
          <label class="form-label" for="deletePassword">@T("MY_ACCOUNT.CURRENT_PASSWORD_LABEL")</label>
          <input id="deletePassword" name="deletePassword" type="password" maxlength="72"
                 autocomplete="current-password" required class="form-control">
        </div>
        <button type="submit" class="btn btn-danger">@T("MY_ACCOUNT.DELETE_SUBMIT")</button>
      </form>
    </div>

  </div>
</div>
  • 第 16–76 行:账户修改:身份、登录名、新密码(可选)及其确认;
  • 第 17 行:客户记录的版本(乐观锁);
  • 第 59–69 行:当前密码,任何修改都需要它;
  • 第 83–91 行:删除,带有确认。同一页面上有两个相互独立的表单:每个表单只提交自己的字段。因此密码字段在这里有不同的名称([deletePassword])和不同的标识符。这个表单没有 [novalidate] 属性:浏览器甚至在触发 [required] 之前,即在询问确认问题之前,就要求填写密码([submit] 事件)。

11.17.2.8. Views/Shared/Error.cshtml

@* =========================================================================
   Views/Shared/Error.cshtml - the error page (400, 403, 404, 500),
   built by ErrorController.
   ========================================================================= *@
@model ErrorModel
<div class="row justify-content-center">
  <div class="col-md-8 col-lg-6">
    <div class="card p-4 text-center">
      <h1 class="display-4 text-danger">@Model.Code</h1>
      <p class="lead">@T(Model.Message)</p>
      <div><a class="btn btn-primary" href="/">@T("ERROR_PAGE.BACK")</a></div>
    </div>
  </div>
</div>
  • 第 9–10 行:由 [ErrorController] 生成的错误页面(400、403、404、500):HTTP 代码和翻译后的消息。它存放在 [Views/Shared] 中,无论哪个控制器请求它,都能找到它。

11.18. 字典

字典与 [NestJS] 版本中的相同,没有任何改动:它们由 [Translator] 服务读取(参见示例 22)。

11.18.1. i18n/fr.json

{
  "APP": {
    "TITLE": "RdvMedecins",
    "LOGOUT": "Se déconnecter",
    "MENU_SCHEDULE": "Agenda",
    "MENU_DOCTORS": "Médecins",
    "MENU_PATIENTS": "Clients",
    "MENU_MY_AREA": "Mon espace"
  },
  "LOGIN": {
    "TITLE": "Connexion",
    "LOGIN_LABEL": "Login",
    "PASSWORD_LABEL": "Mot de passe",
    "SUBMIT": "Se connecter",
    "ERROR": "Login ou mot de passe incorrect.",
    "DEMO_ACCOUNTS": "Comptes de démonstration (mot de passe = login) :",
    "DEMO_ADMIN": "rôle ADMIN : rendez-vous + gestion des médecins et des clients",
    "DEMO_DOCTOR": "rôle DOCTOR : prise et annulation de rendez-vous",
    "DEMO_USER": "rôle USER (patients) : réservation pour eux-mêmes, gestion de leur compte",
    "CREATE_ACCOUNT": "Créer un compte client",
    "CREATE_ACCOUNT_HELP": "Pour créer un compte, recopiez d'abord les caractères de l'image."
  },
  "DOCTOR_DAY_PICKER": {
    "DOCTOR_LABEL": "Médecin",
    "CHOOSE_DOCTOR": "-- choisir un médecin --",
    "DAY_LABEL": "Jour",
    "VIEW_SCHEDULE": "Voir l'agenda"
  },
  "SCHEDULE": {
    "PAGE_TITLE": "Agenda",
    "TITLE_PREFIX": "Agenda du",
    "COLUMN_SLOT": "Créneau",
    "COLUMN_STATUS": "Statut",
    "FREE": "Libre",
    "BOOK": "Réserver",
    "CANCEL_APPOINTMENT": "Annuler",
    "CANCEL_CONFIRM": "Annuler ce rendez-vous ?",
    "EMPTY_STATE": "Choisissez un médecin et un jour, puis cliquez sur « Voir l'agenda ».",
    "NO_SLOTS": "Ce médecin n'a aucun créneau horaire.",
    "BOOKED": "Rendez-vous enregistré.",
    "CANCELLED": "Rendez-vous annulé.",
    "BOOKED_BY_OTHER": "Réservé",
    "ALREADY_BOOKED_INFO": "Vous avez déjà un rendez-vous à venir : annulez-le pour en prendre un autre."
  },
  "BOOKING_DIALOG": {
    "TITLE": "Réserver ce créneau",
    "CLOSE_ARIA": "Fermer",
    "SLOT": "Créneau de {time}",
    "PATIENT_LABEL": "Patient",
    "CHOOSE_PATIENT": "-- choisir un patient --",
    "CANCEL": "Annuler",
    "CONFIRM": "Confirmer"
  },
  "PERSONS": {
    "COLUMN_TITLE": "Titre",
    "COLUMN_FIRSTNAME": "Prénom",
    "COLUMN_LASTNAME": "Nom",
    "COLUMN_LOGIN": "Login",
    "EDIT": "Modifier",
    "DELETE": "Supprimer",
    "SAVE": "Enregistrer",
    "BACK": "Retour à la liste",
    "TITLE_LABEL": "Titre",
    "FIRSTNAME_LABEL": "Prénom",
    "LASTNAME_LABEL": "Nom",
    "LOGIN_LABEL": "Login",
    "PASSWORD_LABEL": "Mot de passe",
    "LOGIN_HELP_CREATE": "Facultatif : par défaut, le nom en minuscules.",
    "LOGIN_HELP_EDIT": "Laisser vide pour ne pas le changer.",
    "PASSWORD_HELP_CREATE": "Facultatif : par défaut, identique au login.",
    "PASSWORD_HELP_EDIT": "Laisser vide pour ne pas le changer.",
    "ACCOUNT_SECTION": "Compte utilisateur"
  },
  "DOCTORS": {
    "TITLE": "Médecins",
    "ADD": "Ajouter un médecin",
    "EDIT": "Modifier un médecin",
    "EMPTY": "Aucun médecin.",
    "DELETE_CONFIRM": "Supprimer ce médecin, ses créneaux horaires et son compte utilisateur ?",
    "ADDED": "Le médecin {name} a été ajouté (login : {login}).",
    "UPDATED": "Le médecin {name} a été modifié.",
    "DELETED": "Le médecin {name} a été supprimé."
  },
  "CLIENTS": {
    "TITLE": "Clients",
    "ADD": "Ajouter un client",
    "EDIT": "Modifier un client",
    "EMPTY": "Aucun client.",
    "DELETE_CONFIRM": "Supprimer ce client, son compte utilisateur et tous ses rendez-vous ?",
    "ADDED": "Le client {name} a été ajouté (login : {login}).",
    "UPDATED": "Le client {name} a été modifié.",
    "DELETED": "Le client {name} a été supprimé."
  },
  "ERROR_PAGE": {
    "TITLE": "Erreur",
    "BACK": "Retour à l'accueil"
  },
  "ERRORS": {
    "LOGIN_TAKEN": "Ce login est déjà utilisé par un autre compte.",
    "DOCTOR_ALREADY_EXISTS": "Un médecin portant ce prénom et ce nom existe déjà.",
    "PATIENT_ALREADY_EXISTS": "Un client portant ce prénom et ce nom existe déjà.",
    "DOCTOR_HAS_APPOINTMENTS": "Ce médecin a des rendez-vous : annulez-les avant de le supprimer.",
    "SLOT_ALREADY_BOOKED": "Ce créneau vient d'être réservé par quelqu'un d'autre.",
    "CONCURRENT_UPDATE": "Cette fiche a été modifiée entre-temps par un autre utilisateur. Revenez à la liste et rouvrez-la avant de recommencer.",
    "DOCTOR_NOT_FOUND": "Ce médecin n'existe pas (ou plus).",
    "PATIENT_NOT_FOUND": "Ce client n'existe pas (ou plus).",
    "SLOT_NOT_FOUND": "Ce créneau n'existe pas (ou plus).",
    "APPOINTMENT_NOT_FOUND": "Ce rendez-vous n'existe pas (ou plus).",
    "INVALID_DATE": "La date demandée n'est pas valide.",
    "CHOOSE_PATIENT": "Choisissez un patient.",
    "INVALID_FORM": "Le formulaire contient des erreurs.",
    "INVALID_TITLE": "Choisissez un titre dans la liste.",
    "FIRSTNAME_REQUIRED": "Le prénom est obligatoire.",
    "FIRSTNAME_TOO_LONG": "Le prénom ne doit pas dépasser 20 caractères.",
    "LASTNAME_REQUIRED": "Le nom est obligatoire.",
    "LASTNAME_TOO_LONG": "Le nom ne doit pas dépasser 20 caractères.",
    "INVALID_LOGIN": "30 caractères au plus : lettres minuscules non accentuées, chiffres, point, tiret, souligné.",
    "PASSWORD_TOO_LONG": "Le mot de passe ne doit pas dépasser 72 caractères.",
    "SESSION_EXPIRED": "Votre session a expiré : reconnectez-vous.",
    "BAD_REQUEST": "La requête est invalide.",
    "FORBIDDEN": "Votre rôle ne vous permet pas d'accéder à cette page.",
    "NOT_FOUND": "Cette page n'existe pas.",
    "SERVER_ERROR": "Une erreur inattendue s'est produite. Réessayez plus tard.",
    "TOO_MANY_ATTEMPTS": "Trop de tentatives infructueuses. Réessayez dans {minutes} minute(s).",
    "WRONG_CAPTCHA": "Les caractères recopiés ne correspondent pas à l'image. Une nouvelle image vous est proposée.",
    "TOO_MANY_ACCOUNTS": "Trop de comptes ont été créés depuis votre connexion. Réessayez dans {minutes} minute(s).",
    "LOGIN_REQUIRED": "Le login est obligatoire.",
    "PASSWORD_REQUIRED": "Le mot de passe est obligatoire.",
    "PASSWORD_TOO_SHORT": "Le mot de passe doit comporter au moins {min} caractères.",
    "CONFIRMATION_REQUIRED": "Confirmez le mot de passe.",
    "PASSWORDS_DIFFER": "La confirmation ne correspond pas au mot de passe.",
    "CURRENT_PASSWORD_REQUIRED": "Saisissez votre mot de passe actuel.",
    "WRONG_CURRENT_PASSWORD": "Mot de passe actuel incorrect.",
    "PAST_DATE": "On ne peut pas prendre de rendez-vous à une date passée.",
    "PATIENT_HAS_UPCOMING_APPOINTMENT": "Ce patient a déjà un rendez-vous à venir : il faut l'annuler avant d'en prendre un autre.",
    "CAPTCHA_BEFORE_ACCOUNT": "Pour créer un compte, recopiez d'abord correctement les caractères de l'image, puis cliquez sur « Créer un compte client »."
  },
  "CAPTCHA": {
    "LABEL": "Recopiez les caractères de l'image",
    "IMAGE_ALT": "Image de vérification anti-robots",
    "NEW_IMAGE": "Autre image",
    "HELP": "Majuscules ou minuscules, peu importe."
  },
  "REGISTRATION": {
    "TITLE": "Créer un compte client",
    "INTRO": "Ce compte vous permettra de prendre vous-même vos rendez-vous.",
    "LOGIN_HELP": "Lettres minuscules non accentuées, chiffres, point, tiret, souligné.",
    "PASSWORD_HELP": "Au moins {min} caractères.",
    "SUBMIT": "Créer mon compte",
    "BACK_TO_LOGIN": "Retour à la connexion",
    "DONE": "Votre compte a été créé. Vous pouvez vous connecter avec le login {login}."
  },
  "ACCOUNT": {
    "CONFIRMATION_LABEL": "Confirmation du mot de passe"
  },
  "AREA": {
    "TITLE": "Mon espace",
    "HELLO": "Bonjour {name}",
    "MANAGE_ACCOUNT": "Gérer mon compte",
    "MANAGE_ACCOUNT_HELP": "Modifier mes informations, mon mot de passe, ou supprimer mon compte.",
    "VIEW_SCHEDULE": "Voir un agenda",
    "VIEW_SCHEDULE_HELP": "Consulter l'agenda d'un médecin et réserver un créneau.",
    "MY_APPOINTMENT": "Mon rendez-vous",
    "SEE_IN_SCHEDULE": "voir dans l'agenda",
    "CANCEL_APPOINTMENT": "Annuler ce rendez-vous",
    "NO_APPOINTMENT": "Vous n'avez aucun rendez-vous à venir."
  },
  "MY_ACCOUNT": {
    "TITLE": "Gérer mon compte",
    "NEW_PASSWORD_LABEL": "Nouveau mot de passe",
    "CURRENT_PASSWORD_LABEL": "Mot de passe actuel",
    "CURRENT_PASSWORD_HELP": "Obligatoire pour enregistrer une modification.",
    "BACK": "Retour à mon espace",
    "DELETE_TITLE": "Supprimer mon compte",
    "DELETE_HELP": "Votre compte sera définitivement supprimé, ainsi que tous vos rendez-vous.",
    "DELETE_CONFIRM": "Supprimer définitivement votre compte ? Votre rendez-vous éventuel sera annulé.",
    "DELETE_SUBMIT": "Supprimer mon compte",
    "UPDATED": "Votre compte a été modifié.",
    "DELETED": "Votre compte a été supprimé."
  },
  "CONFIRMATION": {
    "TITLE": "Confirmation",
    "NO": "Non, revenir",
    "YES": "Oui, confirmer"
  }
}
  • 各节按页面([LOGIN]、[SCHEDULE]、[AREA]……)或按主题([ERRORS]、[CONFIRMATION])对文本进行分组。有些名称([DOCTOR_DAY_PICKER]、[BOOKING_DIALOG])对应 [Angular] 客户端的组件,其字典由 [NestJS] 版本继承而来;
  • 第 80 行:带有两个参数的文本,[{name}] 和 [{login}],它们在翻译时被替换;
  • 第 98–136 行:错误消息。这些是业务层中的 [BusinessException] 组件、表单验证特性([ErrorMessage = "ERRORS.FIRSTNAME_REQUIRED"])、控制器和异常过滤器所使用的键。其中三个带有参数:[{minutes}] 和 [{min}]。

11.18.2. i18n/en.json

{
  "APP": {
    "TITLE": "RdvMedecins",
    "LOGOUT": "Log out",
    "MENU_SCHEDULE": "Schedule",
    "MENU_DOCTORS": "Doctors",
    "MENU_PATIENTS": "Patients",
    "MENU_MY_AREA": "My area"
  },
  "LOGIN": {
    "TITLE": "Login",
    "LOGIN_LABEL": "Login",
    "PASSWORD_LABEL": "Password",
    "SUBMIT": "Log in",
    "ERROR": "Incorrect login or password.",
    "DEMO_ACCOUNTS": "Demo accounts (password = login):",
    "DEMO_ADMIN": "ADMIN role: appointments + doctor and patient management",
    "DEMO_DOCTOR": "DOCTOR role: booking and cancelling appointments",
    "DEMO_USER": "USER role (patients): booking for themselves, managing their account",
    "CREATE_ACCOUNT": "Create a patient account",
    "CREATE_ACCOUNT_HELP": "To create an account, first type the characters shown in the image."
  },
  "DOCTOR_DAY_PICKER": {
    "DOCTOR_LABEL": "Doctor",
    "CHOOSE_DOCTOR": "-- choose a doctor --",
    "DAY_LABEL": "Day",
    "VIEW_SCHEDULE": "View schedule"
  },
  "SCHEDULE": {
    "PAGE_TITLE": "Schedule",
    "TITLE_PREFIX": "Schedule for",
    "COLUMN_SLOT": "Slot",
    "COLUMN_STATUS": "Status",
    "FREE": "Free",
    "BOOK": "Book",
    "CANCEL_APPOINTMENT": "Cancel",
    "CANCEL_CONFIRM": "Cancel this appointment?",
    "EMPTY_STATE": "Choose a doctor and a day, then click \"View schedule\".",
    "NO_SLOTS": "This doctor has no time slots.",
    "BOOKED": "Appointment booked.",
    "CANCELLED": "Appointment cancelled.",
    "BOOKED_BY_OTHER": "Booked",
    "ALREADY_BOOKED_INFO": "You already have an upcoming appointment: cancel it to book another one."
  },
  "BOOKING_DIALOG": {
    "TITLE": "Book this slot",
    "CLOSE_ARIA": "Close",
    "SLOT": "Slot {time}",
    "PATIENT_LABEL": "Patient",
    "CHOOSE_PATIENT": "-- choose a patient --",
    "CANCEL": "Cancel",
    "CONFIRM": "Confirm"
  },
  "PERSONS": {
    "COLUMN_TITLE": "Title",
    "COLUMN_FIRSTNAME": "First name",
    "COLUMN_LASTNAME": "Last name",
    "COLUMN_LOGIN": "Login",
    "EDIT": "Edit",
    "DELETE": "Delete",
    "SAVE": "Save",
    "BACK": "Back to the list",
    "TITLE_LABEL": "Title",
    "FIRSTNAME_LABEL": "First name",
    "LASTNAME_LABEL": "Last name",
    "LOGIN_LABEL": "Login",
    "PASSWORD_LABEL": "Password",
    "LOGIN_HELP_CREATE": "Optional: defaults to the last name in lower case.",
    "LOGIN_HELP_EDIT": "Leave empty to keep it unchanged.",
    "PASSWORD_HELP_CREATE": "Optional: defaults to the login.",
    "PASSWORD_HELP_EDIT": "Leave empty to keep it unchanged.",
    "ACCOUNT_SECTION": "User account"
  },
  "DOCTORS": {
    "TITLE": "Doctors",
    "ADD": "Add a doctor",
    "EDIT": "Edit a doctor",
    "EMPTY": "No doctors.",
    "DELETE_CONFIRM": "Delete this doctor, their time slots and their user account?",
    "ADDED": "Doctor {name} has been added (login: {login}).",
    "UPDATED": "Doctor {name} has been updated.",
    "DELETED": "Doctor {name} has been deleted."
  },
  "CLIENTS": {
    "TITLE": "Patients",
    "ADD": "Add a patient",
    "EDIT": "Edit a patient",
    "EMPTY": "No patients.",
    "DELETE_CONFIRM": "Delete this patient, their user account and all their appointments?",
    "ADDED": "Patient {name} has been added (login: {login}).",
    "UPDATED": "Patient {name} has been updated.",
    "DELETED": "Patient {name} has been deleted."
  },
  "ERROR_PAGE": {
    "TITLE": "Error",
    "BACK": "Back to the home page"
  },
  "ERRORS": {
    "LOGIN_TAKEN": "This login is already used by another account.",
    "DOCTOR_ALREADY_EXISTS": "A doctor with this first and last name already exists.",
    "PATIENT_ALREADY_EXISTS": "A patient with this first and last name already exists.",
    "DOCTOR_HAS_APPOINTMENTS": "This doctor has appointments: cancel them before deleting the doctor.",
    "SLOT_ALREADY_BOOKED": "This slot has just been booked by someone else.",
    "CONCURRENT_UPDATE": "This record was changed by another user in the meantime. Go back to the list and reopen it before trying again.",
    "DOCTOR_NOT_FOUND": "This doctor does not exist (any more).",
    "PATIENT_NOT_FOUND": "This patient does not exist (any more).",
    "SLOT_NOT_FOUND": "This slot does not exist (any more).",
    "APPOINTMENT_NOT_FOUND": "This appointment does not exist (any more).",
    "INVALID_DATE": "The requested date is not valid.",
    "CHOOSE_PATIENT": "Choose a patient.",
    "INVALID_FORM": "The form contains errors.",
    "INVALID_TITLE": "Choose a title from the list.",
    "FIRSTNAME_REQUIRED": "The first name is required.",
    "FIRSTNAME_TOO_LONG": "The first name must not exceed 20 characters.",
    "LASTNAME_REQUIRED": "The last name is required.",
    "LASTNAME_TOO_LONG": "The last name must not exceed 20 characters.",
    "INVALID_LOGIN": "At most 30 characters: unaccented lower-case letters, digits, dot, hyphen, underscore.",
    "PASSWORD_TOO_LONG": "The password must not exceed 72 characters.",
    "SESSION_EXPIRED": "Your session has expired: please log in again.",
    "BAD_REQUEST": "The request is invalid.",
    "FORBIDDEN": "Your role does not allow you to access this page.",
    "NOT_FOUND": "This page does not exist.",
    "SERVER_ERROR": "An unexpected error occurred. Please try again later.",
    "TOO_MANY_ATTEMPTS": "Too many failed attempts. Try again in {minutes} minute(s).",
    "WRONG_CAPTCHA": "The characters you typed do not match the image. A new image is shown.",
    "TOO_MANY_ACCOUNTS": "Too many accounts have been created from your connection. Try again in {minutes} minute(s).",
    "LOGIN_REQUIRED": "The login is required.",
    "PASSWORD_REQUIRED": "The password is required.",
    "PASSWORD_TOO_SHORT": "The password must be at least {min} characters long.",
    "CONFIRMATION_REQUIRED": "Please confirm the password.",
    "PASSWORDS_DIFFER": "The confirmation does not match the password.",
    "CURRENT_PASSWORD_REQUIRED": "Enter your current password.",
    "WRONG_CURRENT_PASSWORD": "Incorrect current password.",
    "PAST_DATE": "Appointments cannot be booked for a past date.",
    "PATIENT_HAS_UPCOMING_APPOINTMENT": "This patient already has an upcoming appointment: it must be cancelled before booking another one.",
    "CAPTCHA_BEFORE_ACCOUNT": "To create an account, first type the characters shown in the image correctly, then click \"Create a patient account\"."
  },
  "CAPTCHA": {
    "LABEL": "Type the characters shown in the image",
    "IMAGE_ALT": "Anti-robot verification image",
    "NEW_IMAGE": "Another image",
    "HELP": "Upper or lower case, it does not matter."
  },
  "REGISTRATION": {
    "TITLE": "Create a patient account",
    "INTRO": "With this account you can book your own appointments.",
    "LOGIN_HELP": "Unaccented lower-case letters, digits, dot, hyphen, underscore.",
    "PASSWORD_HELP": "At least {min} characters.",
    "SUBMIT": "Create my account",
    "BACK_TO_LOGIN": "Back to login",
    "DONE": "Your account has been created. You can now log in with the login {login}."
  },
  "ACCOUNT": {
    "CONFIRMATION_LABEL": "Confirm password"
  },
  "AREA": {
    "TITLE": "My area",
    "HELLO": "Hello {name}",
    "MANAGE_ACCOUNT": "Manage my account",
    "MANAGE_ACCOUNT_HELP": "Change my details or password, or delete my account.",
    "VIEW_SCHEDULE": "View a schedule",
    "VIEW_SCHEDULE_HELP": "See a doctor's schedule and book a slot.",
    "MY_APPOINTMENT": "My appointment",
    "SEE_IN_SCHEDULE": "see in the schedule",
    "CANCEL_APPOINTMENT": "Cancel this appointment",
    "NO_APPOINTMENT": "You have no upcoming appointment."
  },
  "MY_ACCOUNT": {
    "TITLE": "Manage my account",
    "NEW_PASSWORD_LABEL": "New password",
    "CURRENT_PASSWORD_LABEL": "Current password",
    "CURRENT_PASSWORD_HELP": "Required to save any change.",
    "BACK": "Back to my area",
    "DELETE_TITLE": "Delete my account",
    "DELETE_HELP": "Your account will be permanently deleted, together with all your appointments.",
    "DELETE_CONFIRM": "Permanently delete your account? Any appointment you have will be cancelled.",
    "DELETE_SUBMIT": "Delete my account",
    "UPDATED": "Your account has been updated.",
    "DELETED": "Your account has been deleted."
  },
  "CONFIRMATION": {
    "TITLE": "Confirmation",
    "NO": "No, go back",
    "YES": "Yes, confirm"
  }
}

英文字典的键与之完全相同。

11.19. 静态文件

[wwwroot] 文件夹由 [UseStaticFiles] 提供(参见示例 15)。[wwwroot/lib/bootstrap] 文件夹包含 [Bootstrap] (其样式表 [css/bootstrap.min.css] 及其许可证),这些内容不予展示。

11.19.1. wwwroot/css/styles.css

/* =========================================================================
   wwwroot/css/styles.css - a few settings on top of Bootstrap
   (taken from src/styles.css of the Angular client, via the NestJS project).
   ========================================================================= */

body {
  background-color: #f5f7fa;
}

.free-slot:hover {
  background-color: #e9f7ef;
}

/* -------------------------------------------------------------------------
   .error-zone: the error messages, at the bottom of the page, on a light pink background
   (see Views/Shared/_Errors.cshtml).
   position: sticky + bottom: if the page is taller than the window (a
   schedule of 12 slots, for example), the zone stays stuck to the bottom of the
   window instead of disappearing below the fold - without ever
   covering the content when the page is short.
   z-index: above the grey background of the booking dialog (.modal-backdrop).
   ------------------------------------------------------------------------- */
.error-zone {
  position: sticky;
  bottom: 1rem;
  z-index: 1060;
  margin-top: 1.5rem;
  padding: 0.75rem 1rem;
  background-color: #fdecef; /* 浅粉色 */
  border: 1px solid #f5c2c7;
  border-radius: 0.375rem;
  color: #842029;
}

/* 患者"我的空间"页面中的两个大选项 */
.option-card {
  transition: border-color 0.15s, box-shadow 0.15s;
}

.option-card:hover {
  border-color: #0d6efd;
  box-shadow: 0 0.25rem 0.75rem rgba(13, 110, 253, 0.15);
}

/* 验证码图片(150 x 50 像素的 SVG) */
.captcha-image svg {
  display: block;
  border: 1px solid #dee2e6;
  border-radius: 0.375rem;
}
  • 第 10–12 行:可预约的时间段在鼠标悬停时变色;
  • 第 23–33 行:错误区域,背景为浅粉色。[position: sticky] 和 [bottom: 1rem]:如果页面比窗口高,该区域会保持在窗口底部,而不是滚出屏幕;[z-index] 把它置于预约窗口的灰色背景之上;
  • 第 36–43 行:“我的区域”的两个选项会对鼠标悬停作出响应;
  • 第 46–50 行:验证码(CAPTCHA)图像的边框。

11.19.2. wwwroot/js/app.js

// =========================================================================
// wwwroot/js/app.js:应用程序中唯一的 JavaScript。
// -------------------------------------------------------------------------
// 整个应用在没有 JavaScript 时也能工作。此脚本增加了一项
// 便利功能:在发送带有 data-confirmation="..." 属性的表单之前,
// 会用模态对话框询问"确定吗?"
// (对话框本身在页面中:Views/Shared/_Confirmation.cshtml)。
// 若禁用了 JavaScript,表单会直接发送,
// 不带确认,不会出任何问题("渐进增强"原则)。
//
// 为什么不用 window.confirm()?它的对话框无法设置样式,
// 其按钮使用浏览器的语言,而不是页面的语言。
// =========================================================================

(() => {
  const modal = document.getElementById('confirmation-modal');
  if (!modal) {
    return;
  }
  const message = document.getElementById('confirmation-modal-message');
  const noButton = modal.querySelector('.modal-footer [data-action="no"]');

  let pendingForm = null; // 用户确认后要发送的表单
  let previousFocus = null; // 关闭时要把焦点还给的元素

  function open(form) {
    pendingForm = form;
    previousFocus = document.activeElement;
    // 用 textContent(而不是 innerHTML):消息作为文本显示,
    // 绝不会被解释为 HTML
    message.textContent = form.dataset.confirmation;
    modal.classList.remove('d-none');
    // 焦点落在"否"上:手滑按下 Enter 不会删除任何内容
    noButton.focus();
  }

  function close() {
    modal.classList.add('d-none');
    pendingForm = null;
    if (previousFocus) {
      previousFocus.focus();
    }
  }

  // 1. 我们拦截需要确认的表单的发送
  document.querySelectorAll('form[data-confirmation]').forEach((form) => {
    form.addEventListener('submit', (event) => {
      event.preventDefault();
      open(form);
    });
  });

  // 2. 对话框的按钮(是 / 否 / 关闭叉号)
  modal.addEventListener('click', (event) => {
    const action = event.target.closest('[data-action]')?.dataset.action;
    if (action === 'yes') {
      const form = pendingForm;
      close();
      // form.submit() 发送表单时不会再次触发
      // 'submit' 事件:不会再次请求确认
      form.submit();
    } else if (action === 'no') {
      close();
    } else if (event.target.classList.contains('modal')) {
      close(); // 点击对话框外部的灰色背景
    }
  });

  // 3. 键盘:Escape 关闭对话框;Tab 停留在对话框内部
  //    (否则焦点会跑到后面变灰的页面上)
  modal.addEventListener('keydown', (event) => {
    if (event.key === 'Escape') {
      close();
    } else if (event.key === 'Tab') {
      const buttons = [...modal.querySelectorAll('button')];
      const first = buttons[0];
      const last = buttons[buttons.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    }
  });
})();

示例 21 中确认窗口的脚本,增加了键盘处理。它遵循同样的渐进增强原则:没有 [JavaScript] 时,表单会不经确认直接提交,应用程序仍然可以正常工作。

  • 第 16–19 行:没有确认窗口的页面无事可做;
  • 第 24 行:窗口打开之前拥有键盘焦点(接收按键的元素)的元素:窗口关闭时,焦点会返回到它;
  • 第 26–35 行:焦点放在“否,返回”上;意外按下 Enter 键不会删除任何内容;
  • 第 37–43 行:窗口被隐藏,焦点被恢复;
  • 第 46–51 行:我们拦截带有属性 [data-confirmation] 的表单的提交,与示例 21 中一样;
  • 第 54–67 行:“是”、“否”、关闭按钮,以及点击窗口外部。[closest('[data-action]')] 会找到包含该属性的元素,即使点击的是其内部的元素。当找不到元素时,运算符 [?.] 返回 [undefined] 而不是失败;
  • 第 71–86 行:Esc 键关闭窗口;Tab 键(以及 Shift+Tab)使焦点在窗口内的按钮之间循环,而不是移到其后变灰的页面上。