XSD Validation – Validating Objects with XSDs: Is Re-Serializing Redundant?

serializationvalidationwcfxml

Context:

I've got a web service that deals with request / response objects. There are strict, externally-defined schemas constraining both the structure and the content of both requests and responses. I need to validate all requests as they are received and all responses before they are sent back (on the web service end of the wire).

I don't want to replicate the validation rules in code, so I'll be validating serialized request / response objects (XML), probably using XmlReader as a starting point (for speed). It'll be 1-way object –> XML validation method that screams if validation fails, otherwise the original object will be used for the actual work.

I'm using WCF, but with XMLSerializer as the schemas are complex and I need the additional XSD support.

Question:

1) Is there a way to avoid re-serializing the objects as they hit my end of the wire? Ideally I'd like to get at the XML before it's de-serialized on the way in, and after it's serialized, just before it goes, on the way out.

I'm aware of [OnSerializing] and [OnSerialized] annotations, but they won't work with XMLSerializer. I don't think I should be writing ReadXml() and WriteXml() using IXmlSerializable either – the schemas are complex and subject to change.

2) Given the XML documents are quite small (122kb seems to be the top end in the sample data set I have) am I right in asserting that the performance hit of re-serializing will be negligible?

3) Any better ideas?

Best Answer

To answer my own question: yes re-serializing would have been redundant.

The answer I was looking for was to use Message Inspectors - job done.