Hands-On Full:Stack Web Development with ASP.NET Core
上QQ阅读APP看书,第一时间看更新

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: