Model validation

http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
In WEBAPi, you can use attributes from System.ComponentModel.DataAnnotations namespace to set validation rules for properties on your models.
image
use ModelState.IsValid to validate the model.

Under-Posting
– Client posting data that are incomplete, e.g.,
image (It’s missing Price and Weight)
But since they’re not required, so JSON formatter automatically set their default to 0.
image
If you want to distinguish 0 and NULL, do this:
(1) Make the property [Required]
(2) Make the property nullable

image

Over-Posting – Client posting more data than you expected, such as:
image
JSON simply ignores the value.
If there is a property in your model that you don’t want anyone to change/update, then create a DTO and serve it to the client. such as:
Your model:
image
Your DTO:
image
Handling Validation errors
Use action filter to catch invalidate ModelState
image
If model state invalid, it send a HTTP response (action is not invoked)
image

To apply the filter to all actions (the whole site), add this to the global.asax
image
10:13pm, 01/25/2013

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s