官术网_书友最值得收藏!

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. 

Starting from ASP.NET Core 2.1, validation checks are done automatically when you decorate your controller with the [ApiController] attribute, and the  BadRequest response is returned if the validation fails.

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:

主站蜘蛛池模板: 洞口县| 石台县| 嵩明县| 鄄城县| 洛宁县| 容城县| 孟州市| 吉木乃县| 铁岭市| 新和县| 福安市| 晋城| 富宁县| 长兴县| 莱州市| 明星| 苗栗市| 白沙| 鹤岗市| 剑河县| 泸州市| 新丰县| 达尔| 奎屯市| 永顺县| 巴南区| 蓝山县| 长治市| 伊宁市| 河源市| 平阳县| 万盛区| 南雄市| 五河县| 宜兰市| 清河县| 江都市| 南陵县| 驻马店市| 马龙县| 平邑县|