Those who know me are familiar with my fondness for XSD validation in the context of Web services. I
wrote about it quite a bit for ASMX and shipped some sample validation extensions that made it easy to turn on XSD or business rules (via XPath assertions) validation with custom attributes.
I wanted to see how hard/easy it would be to do something similar -- enable XSD validation -- in WCF. They didn't ship a validation switch (for which I've longed) as part of the service model so if you're interested in applying XSD validation you'll have to use a technique similar to the one I use in this sample.
You'll find my custom XsdValidationBehavior sample
here.
It implements IDispatchMessageInspector and does most of the work in AfterReceiveRequest. The behavior uses the WsdlExporter to produce the XSD schemas from the service contract type and uses the generated schemas during validation. The trickiest thing to get right was creating a new Message object for the dispatcher to use after I had consumed the one they handed to me. That part turned out to be a bit more tedious than I would have liked, but it's possible that I'm missing something and there's an easier way.
In order to test the sample, add the behavior to your service's behaviors collection manually (as shown here), or you can write a custom attribute or configuration element to enable it declaratively.
using (ServiceHost host = new ServiceHost(typeof(SampleService)))
{
host.Description.Endpoints[0].Behaviors.Add(
new XsdValidationBehavior());
host.Open();
...
Disclaimer: I threw this sample together quickly during a course I was teaching and it has not been tested. I'm providing it to help jump-start those interested in doing something similar.
Posted
Apr 20 2006, 03:15 PM
by
Aaron Skonnard