Asp. Net Web API 2 Lesson 15th -- Model Validation (Model Verification)

Source: Internet
Author: User

Before reading this article, you can also go to the Asp. Net Web API 2 series navigation to view http://www.cnblogs.com/aehyok/p/3446289.html

Reference link Article address http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api

When the client sends data to your Web API, you usually want to verify the data before doing other processing.

In ASP. NET Web APIs, you can use the annotation attributes of the System. ComponentModel. DataAnnotations namespace to set the validation rules for model attributes. Consider the following models:

   Id { ;   Name { ;   Price { ; ,  Weight { ; 

If you have used model verification in ASP. net mvc, it looks similar. The Required annotation attribute indicates that the Name attribute must not be blank. The Range annotation attribute indicates that Weight must be between 0 and.

Assume that the client sends a POST request with the following JSON representation:

{ :, :, : }

As you can see, the client does not contain the Name attribute marked as required. When the Web API converts the JSON into a Product instance, it verifies the Product based on these verification annotation attributes. In the Controller action, you can check whether the model is valid:

               

Model verification does not guarantee the security of client data. Additional verification may be required at other layers of the application (for example, the data layer may force foreign key constraints ).

{:, :}

Here, the client does not specify the Price or Weight value. The JSON formatter assigns the default value (here it is zero) to these missing attributes.

"Under-Posting(Insufficient submission) ":" Under-posting "occurs when the client misses some attributes ". For example, assume that the client sends the following message:

In this case, the model status is valid because zero is the valid value of these attributes. Whether this is a problem depends on your scenario. For example, in an update operation, you may want to distinguish "zero" from "Unset ". To force the client to set a value, construct the property as nullable (which can be empty) and setRequiredAnnotation attributes:

 ? Price { ; ; }

"Over-Posting(Excessive submission) ": the client may also send more data than expected. For example:

{:, :, :}

Here, JSON contains the attributes ("Color") in the Product model "). In this case, the JSON formatter simply ignores the value (but the XML formatter does not ). If your model has a read-only attribute, Over-posting may cause problems. For example:

   Name { ;  Uri Blog { ;   IsAdmin { ; ; }  }

If you do not want the user to update the IsAdmin attribute and upgrade it to the administrator. The most secure policy is to use a model class that strictly matches the allowed client sending:

   Name { ;  Uri Blog { ; }

When verification fails, the Web API does not automatically return the error to the client. This depends on the Controller action to properly check the model status and response.

You can also create an action filter to check the model status before the Controller action is called. The following code demonstrates an example:

    (actionContext.ModelState.IsValid ==              errors =  Dictionary<, IEnumerable<>> (KeyValuePair<, ModelState> keyValue = keyValue.Value.Errors.Select(e =>=

If Model verification fails, this filter returns an HTTP Response containing verification errors. In this case, the Controller action is not called.

HTTP/ /. Jul  ::-Type: application/json; charset=utf--Length: 

If you are using the latest Web API on CodePlex, you can use the HttpError class to return verification errors to the client.HttpErrorThe class is invalid in the RC version (the browser version of the Web API.

You can apply this filter globally to all Web API controllers. InApplication_StartMethod, add the filter to the HttpConfiguration. Filters collection:

 

Another option is to add this filter as an annotation attribute, and you can apply it to individual controller or controller actions:

 

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.