I have a set of services hosted with WCF Web Api, what I need to do is validate the properties inside the models of the app.
In MVC 3 for example I decorate properties in the model like this:
[StringLength(30)]
public string UserName { get; set; }
and then in the controller I proceed like this to verify os the model has met the validation parameters:
[HttpPost]
ActionResult Create(Model myModel)
{
if(ModelState.IsValid(){
Post the model
}
else
{
Don't post the model
}
}
Is there a way to do something similar in WCF Web Api?
Firstly I should say awesome question+answer Daniel
However, I’ve taken it a little further, refined it and added to it.
ValidationHander
I’ve refined this a little. It is now based on a generic
HttpOperationHandlerso it can take theHttpRequestMessage. The reason for this is so that I can return error messages formatted using the correct media type (from the accept header).Extension Methods
The 2 you provided stay virtually the same about from the
descparamter no longer being needed when adding the ValidationHandler in theModelValidationFormethodI’ve added an extra extension method. This is to make sure that all “Resource” classes are validated. This is mainly me being lazy and forgetful. I am forever forgetting to add some class to a list somewhere. (It’s why I write generic windsor installers!)
I made use of the
System.ComponentModel.Composition.Hostingnamespace (formerly known as MEF) for theDirectoryCatalogclass. In this case I’ve just used the namespace ending with “Resources” to find my “Resource” classes. It wouldn’t take much work to change it to use a custom attribute or whatever other way you might prefer to identify which classes are your “Resources”.RestValidationFailure
This is a little helper class I made to allow consistent behaviour for validation failure responses.
So, now I get a nice list (in my preferred mediatype) of all the validation errors.
Enjoy! 🙂