- Hands-On Full:Stack Web Development with ASP.NET Core
- Tamir Dresher Amir Zuker Shay Friedman
- 466字
- 2021-06-10 19:37:31
Model validation
Model validation is ASP.NET Core's ability to run validation rules on the input that your methods receive. The easiest way to define these validation rules is by using validation attributes that are part of the System.ComponentModel.DataAnnotations Namespace (https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations?view=netframework-4.7.2), but you can define custom validations by inheriting from the ValidationAttribute base class. For sophisticated validation rules, I recommend that you use the popular FluentValidation library, available at https://github.com/JeremySkinner/FluentValidation.
There are plenty of built-in validation attributes, but here is a short list of some the most popular ones:
- [Required]: Specifies that a data field value is required
- [Range]: Specifies the allowed numeric range in a data field value
- [MinLength]: Specifies the minimum length that a data field will accept
- [MaxLength]: Specifies the maximum length that a data field will accept
- [EmailAddress]: Specifies that the value of a string field must be in an email address format
For example, the following code block shows how you can define that the NewProductDTO must be set with a value in its Name property of at least 3 characters, and no more than 50:
public class NewProductDTO
{
[Required]
[MinLength(3)]
[MaxLength(50)]
public string Name { get; set; }
public string Category { get; set; }
public string Subcategory { get; set; }
}
Once your validation attributes are positioned, ASP.NET Core will run a validation check automatically when a request is received and the values will be bound to your method parameters. Then, you can inspect the validation result and error messages by using the controller's ModelState property, which is of type ModelStateDictionary. The ModelStateDictionary type represents the state of the attempt to bind values from the HTTP request to the method parameters. It's a dictionary where the key is the name of the parameter and the value is a valid entry. You can use the IsValid property to assert that the request fulfills the required validation rules, like this:
[HttpPost("")]
public ActionResult<NewProductDTO> AddNewProduct([FromBody] NewProductDTO newProduct)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok(newProduct);
}
In the GiveNTake application, we make sure that the details of the new product fulfill the rules we defined, and if not, we send a BadRequest (400 HTTP status code). The controller's BadRequest method accepts the ModelStateDictionary and adds the error message to the HTTP response.
Run the application and use Postman to send two POST requests to the /api/products URL, one with an empty body, and one with the following JSON:
{
"Name" : "",
"Category" : "Appliances",
"Subcategory" : "Microwaves"
}
You should see the following response:

And:

- SOA用戶指南
- 電子政務(wù)效益的經(jīng)濟(jì)分析與評(píng)價(jià)
- Proxmox High Availability
- 計(jì)算機(jī)網(wǎng)絡(luò)安全實(shí)訓(xùn)教程(第二版)
- Go Web Scraping Quick Start Guide
- 網(wǎng)絡(luò)互聯(lián)技術(shù)(實(shí)踐篇)
- Wireshark網(wǎng)絡(luò)分析就這么簡單
- 2018網(wǎng)信發(fā)展報(bào)告
- 城域網(wǎng)與廣域網(wǎng)(第2版)
- 網(wǎng)絡(luò)基礎(chǔ)與網(wǎng)絡(luò)管理項(xiàng)目化教程
- 通信原理及MATLAB/Simulink仿真
- 工業(yè)互聯(lián)網(wǎng)創(chuàng)新實(shí)踐
- 物聯(lián)網(wǎng)工程概論
- 物聯(lián)網(wǎng)工程導(dǎo)論(第3版)
- 局域網(wǎng)組成實(shí)踐