[Boiled ASP. NET Web API2 methodology] (1-6) Model Validation, api2validation

Source: Internet
Author: User

[Boiled ASP. NET Web API2 methodology] (1-6) Model Validation, api2validation

Problem

If you want ASP. NET Web APIs to perform model verification, you can also share some verification logic with ASP. net mvc.

Solution

ASP. NET Web APIs and ASP. net mvc support the same authentication mechanism. They all pass the attribute verification of System. ComponentModel. DataAnnoataions. Use the verification Attributes provided by the Framework to validate the model.

For more fine-grained verification, we can choose to implement IValudateObject in our model (from System. ComponentModel. DataAnnotations ). If all attributes are verified, ASP. NET Web API will call the interface's Validate method. Here we can perform further entity verification. This is the same behavior as MVC, and we can even use the same DTO in Web API and MVC.

Another method is to use a third-party library called FluentValidation (FluentValidation can be downloaded in NuGet), which can build more powerful verification scenarios. In this case, we still need to implement the IValidateObject interface in our model, and also need to rely on the FluentValidation validator, rather than the embedded verification logic.

TIPS: the authentication behavior of ASP. NET Web APIs is the same across hosts.

Working Principle

To read the model from the HTTP Request Body and perform verification, ASP. NET Web API relies on an IBodyModelValidator service. The interface is roughly described in Listing 1-17. However, it is an alternative service. Normally, the default implementation (DefaultBodyModelValidator) is enough for us to use, in HttpConfiguration, it is set to auto-start.

Listing 1-17. IBodyModelValidator Interface

12345 public interface IBodyModelValidator{    bool Validate(object model, Type type, ModelMetadataProvider metadataProvider,    HttpActionContext actionContext, string keyPrefix);}

 

 

There is a service called FormatrtParameterBinding. When the HTTP Request Body is bound to the Action parameter, the valiultbodymodelvalidator Validate method is called. For the validators, They recursively validate the entire object graph, verify each attribute and nested attribute. Web APIs support declarations by using DataAnnotationModelValidatorProviderr. If our model uses the DataMemberAttribute declaration in the WCF mode, we need to use the DataMemberValidatorProvider of the framework.

Finally, our model can implement the IValidatableObject interface, which only exposes a simple method, as shown in Listing 1-18. If the interface is implemented, we need to provide additional verification logic. Once all attributes are verified, ASP. NET Wwb API calls the validateableobject interface's Validate method,

 

Listing 1-18. definition of the IValidateableObject Interface

1234 public interface IValidateableObject{    IEnumerable<ValidationResult> Validate(ValidationContext validationContext);}

 

 

The verification result is represented in ModelStateDictionary form of ASP. NET Web API. ModelState is also available here. This concept is exactly the same as that in ASP. net mvc, but the objects used are different, because Web APIs use their own version of System. Web. Http. Modelbinding. ModelStateDictionary exposes the IsValid attribute, which can be used to check the status of Model verification in the Action.

The declared authentication mechanism is also well integrated into the ASP. NET Web API Help Page, which can provide a semantic description of the API. We will discuss it in detail during the 7-11 period.

Tips the best way to use APIS is to use different models as Request and Response entities. For example, the Object ID is generally only required by the Response model. If the Request needs it, it can be obtained from the URI.

 

Code

Listing 1-19 shows how a model has multiple verifications:

Requiredattriattribute, MaxLengthAttribute, and

RangeAttribute. Next, we can use ModelState to verify the authentication status in the Controller, and respond to appropriate prompts to the caller.

Listing 1-19. Simple Web API Model Verification

123456789101112131415161718192021222324 public class Album{    public int Id { getset; }    [Required(ErrorMessage = "{0} is required")]    [MaxLength(30)]    public string Artist { getset; }    [Required(ErrorMessage = "{0} is required")]    [MaxLength(40)]    public string Title { getset; }    [Range(0, 10, ErrorMessage = "{0} in the range of {1}-{2} is required.")]    public int Rating { getset; }}public class AlbumController : ApiController{    public HttpResponseMessage Post(Album album)    {        if (!ModelState.IsValid)        {            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest,            ModelState));        }        //omitted for brevity    }}

 

 

The general validation of ModelState code can be easily extracted from the Controller into a public part, so that it can be well reused, however, we will introduce this part in detail from 5 to 4.

Now, let's take a look at this scenario. If we want to add two additional attributes Rating and Starred to the model and expand model verification at the same time, verification requires that at least one of the two attributes is required. Although it is difficult to declare the entanglement between two attributes, please do not forget that IValidateableObject can help us. We can use the Validata method in the interface to check the status of the entire model and return the corresponding ValidationResult. The code we want to modify is shown in Listing 1-20.

 

Listing 1-20. Modifying ASP. NET Web APIs depends on IValidateableObject Verification

1234567891011121314151617181920212223 public class Album : IValidatableObject{    public int Id { getset; }      [Required(ErrorMessage = "{0} is required")]    [MaxLength(30)]    public string Artist { getset; }      [Required(ErrorMessage = "{0} is required")]    [MaxLength(40)]    public string Title { getset; }      public int? Rating { getset; }    public bool? Starred { getset; }      public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)    {        if (!(Rating.HasValue && Rating > 0 && Rating < 10) || (Starred.HasValue && Starred.Value))        {            yield return new ValidationResult("You must set either the Rating in the 0-9 range orStarred flag.");        }    }}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.