- 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:

- 通信網(wǎng)絡基礎與設備
- Modern JavaScript Web Development Cookbook
- 物聯(lián)網(wǎng)安全:理論、實踐與創(chuàng)新
- Building Django 2.0 Web Applications
- Learning QGIS 2.0
- 數(shù)字通信同步技術的MATLAB與FPGA實現(xiàn):Altera/Verilog版(第2版)
- SSL VPN : Understanding, evaluating and planning secure, web/based remote access
- 物聯(lián)網(wǎng)通信技術
- 物聯(lián)網(wǎng)之霧:基于霧計算的智能硬件快速反應與安全控制
- 紅藍攻防:構建實戰(zhàn)化網(wǎng)絡安全防御體系
- Getting Started with nopCommerce
- 計算機通信網(wǎng)絡安全
- 移動互聯(lián)網(wǎng)環(huán)境下的核心網(wǎng)剖析及演進
- 黑客與反黑工具使用詳解
- Corona SDK Application Design