0 Comments
Nowadays, WebAPI is widely used for building a RESTful service. Given the fact that Web API can automatically serialize model to JSON format, so Json becomes a very common/popular argument for WebAPI.

The question is how to effectively validate the Json object before processing your business logic. Normally, you might do something like this

if (string.isNullEmpty(object.a)){
//your logical here
}

Thinking if you have 10 properties, you will have to check 10 times and the code will be pretty nasty. So the solution below is attempted to provide an elegant way for validating the JSON object.

Solution
Implement custom ValidationAttributeto the property. Look at the example below, NotNullableAttribute is a customValidationAttribute which will evaluate the value. If it's null, it will throw a NoNullAllowedException.

For example:

[NotNullable(ErrorMessage = "product field can not be null")]
public string Product { get; set; }

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class NotNullableAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value ==null){
//place your logical here
throw new NoNullAllowedException(ErrorMessage);
}

return true;
}
}

If you don't want to write your own code, here is theNuGet package, or you can run the following command in the Package Manager Console.

PM> Install-Package ObjectPropertyValidator


Usage of the NuGet Package

1. Step 1
Create your own class
public class Customer
{
[NotNullable]
public string Name { get; set; }

[NotEmptyWithValidData( Pattern= @"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$")]
public string Email { get; set; }

[NotEmptyWithValidData(MaxLength =10, MinLength = 10)]
public string Phone { get; set; }
}

2.Step 2
Create your WebAPI.

[HttpPost]
public HttpResponseMessage Post(Customer customer)
{
// the argument customerwill be validated before reach your code below.
}
Conclusion
As you can see above, with the solution less code is required for data validation, and it's completely reusable.
Post comment