第五章 模型綁定和數(shù)據(jù)驗證
5.1 模型綁定基礎(chǔ)
什么是模型綁定
模型綁定是ASP.NET Core的一個核心功能,它自動將HTTP請求數(shù)據(jù)(路由參數(shù)、查詢字符串、表單數(shù)據(jù)、JSON等)映射到動作方法的參數(shù)或模型對象。模型綁定簡化了從HTTP請求中提取數(shù)據(jù)的過程,讓開發(fā)者能夠直接使用強類型對象而非手動解析請求。
綁定源特性
ASP.NET Core提供了特性來明確指定數(shù)據(jù)應(yīng)該從哪個源綁定:
| 特性 | 數(shù)據(jù)源 | 示例 |
|---|---|---|
| [FromRoute] | 路由參數(shù) | /api/products/{id} |
| [FromQuery] | 查詢字符串 | /api/products?category=electronics |
| [FromBody] | 請求正文 | HTTP POST/PUT/PATCH的JSON或XML數(shù)據(jù) |
| [FromForm] | 表單數(shù)據(jù) | 多部分表單數(shù)據(jù)或x-www-form-urlencoded |
| [FromHeader] | HTTP頭部 | Authorization: Bearer token |
| [FromServices] | 服務(wù)容器(依賴注入) | 注入的服務(wù) |
5.2 模型驗證
內(nèi)置驗證特性
ASP.NET Core提供了一組內(nèi)置的驗證特性,可用于驗證模型:
| 特性 | 描述 | 示例 |
|---|---|---|
| [Required] | 屬性不能為null | [Required] |
| [StringLength] | 字符串長度限制 | [StringLength(50, MinimumLength = 3)] |
| [Range] | 數(shù)值范圍限制 | [Range(1, 100)] |
| [RegularExpression] | 正則表達式匹配 | [RegularExpression(@"^[A-Z]{2}\d{4}$")] |
| [EmailAddress] | 電子郵件格式 | [EmailAddress] |
| [Phone] | 電話號碼格式 | [Phone] |
| [Url] | URL格式 | [Url] |
例如,為產(chǎn)品模型添加驗證:
public class Product
{
public int Id { get; set; }
[Required]
[StringLength(100, MinimumLength = 3)]
public string Name { get; set; }
[Required]
[StringLength(500)]
public string Description { get; set; }
[Range(0.01, 10000)]
public decimal Price { get; set; }
[Range(0, 1000)]
public int StockQuantity { get; set; }
[Url]
public string ImageUrl { get; set; }
}


浙公網(wǎng)安備 33010602011771號