Question

I have some REST web services implemented in WCF. I wish to make these services return "Bad Request" when the xml contains invalid elements.

The xml serialization is being handled by XmlSerializer. By default XmlSerializer ignores unknown elements. I know it is possible to hook XmlSerializer.UnknownElement and throw an exception from this handler, but because this is in WCF I have no control over serialization. Any ideas how I might implement this behavior.

Was it helpful?

Solution

"I know it is possible to hook XmlSerializer.UnknownElement and throw an exception from this handler, but because this is in WCF I have no control over serialization"

Its actually possible to do this...

In a WCF project that I worked on, we did something similar using the IDispatchMessageFormatter interface.

More information can be found here http://nayyeri.net/blog/use-idispatchmessageformatter-and-iclientmessageformatter-to-customize-messages-in-wcf/

It allows you peak at the message headers, control serialization/deserialization, return status codes etc.

OTHER TIPS

Maybe you can return your own type implementing IXmlSerializable and thorw the exception you want in the ReadXml and WriteXml methods...

This is from vague memory as I don't have all the code to hand, but you can create a custom Message (inherit for the class "Message") type to return in your REST services and override certain methods to create custom responses.

    protected override void OnWriteMessage(XmlDictionaryWriter writer)
    {
        ...
    }

    protected override void OnWriteStartEnvelope(XmlDictionaryWriter writer)
    {
        ...
    }

    protected override void OnWriteStartBody(XmlDictionaryWriter writer)
    {
        ...
    }

    protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
    {
        ...
    }

Not a complete answer, but might push you down the right path.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top