is there a way to enforce requirdness on datamembers

54 views
Skip to first unread message

Ash

unread,
Jul 24, 2012, 8:43:45 PM7/24/12
to servic...@googlegroups.com
class MyDto
{
 public string Name{get;set;}
 public int Count{get;set;}
}

In the above DTO both fields are required, but if user of the api doesn't send 'Count' in the request body then it will be set to zero.
Is there a way to throw some validation exception during deserialization when a user missed a required data member in the data contract?

Demis Bellot

unread,
Jul 24, 2012, 8:56:35 PM7/24/12
to servic...@googlegroups.com

Sure, in your service :)

if (request.Count = default(int) throw new ArgumentNullException("Count"); 

You can also specify this validation rule in a custom validator:


Although this will throw for 0. 
Note: In your Request DTO you could've also specified `int? Count` which if it doesn't exist will be null so doesn't clash with a valid '0' value.

You can check to see if the param was present in any of the HTTP request with:

if (base.RequestContext.Get<IHttpRequest>().GetParam("Count") == null) throw new ...

If you want to be more specific, you can verify for existence in IHttpRequest.QueryString and IHttpRequest.FormData 

There's also a Custom Request Binder option, to take over full control over the serialization yourself:
Cheers,
Reply all
Reply to author
Forward
0 new messages