Receive invalid xml through WCF adapter

Recently I had a small project that involved getting exchange rate data from the website of the Central Bank of the Republic of Turkey (CBRT).

Basically I just needed to do an HTTP GET to a specific URL, and that would give me back an xml with the exchange rate information I needed.
So my first thought was to just use a WCF sendport with the webHttpBinding to download this.

The first test I make results in the following error message.
System.Xml.XmlException: Processing instructions (other than the XML declaration) and DTDs are not supported. Line 2, position 2.

When I looked closer at the XML I get back, I saw that it contained a reference to an xsl file to make the file readable through a browser.
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="isokur.xsl"?>
<Tarih_Date Tarih="07.07.2017" Date="07/07/2017"  Bulten_No="2017/131" >

It seems that the standard WCF adapter has some issues with this. So I had to write a WCF extension to make it work. The right option here was a custom Message Encoder.
As a base I used the CustomerTextMessageEncoder sample (https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/custom-message-encoder-custom-text-encoder). Just to make my life a bit easier.

I changed the "ReadMessage" method to ignore that line in the xml message.
public override Message ReadMessage(System.IO.Stream stream, int maxSizeOfHeaders, string contentType)
{
    XmlReaderSettings xsettings = new XmlReaderSettings();
    xsettings.IgnoreProcessingInstructions = true;
    XmlReader reader = XmlReader.Create(stream,xsettings);
    return Message.CreateMessage(reader, maxSizeOfHeaders, this.MessageVersion);
}

I configured my sendport as a WCF-Custom with custom binding like this
After this it worked like a charm. Basically, if you need to change the XML in some way before it can be parsed, you can use the same strategy. Just write your own code in the "ReadMessage" method and you should be able to make it work.

Comments

Popular posts from this blog

Query SAP HANA from BizTalk

Azure API Management : Exposing backend SOAP service as REST