Things I Felt Like Posting

Flatten WCF WSDL on Demand

If you've done any work with WCF and non .NET clients, you've probably had the need to make WCF emit a flattened WSDL that doesn't use xsd includes. You've probably run across Tomas Restrepo's InlineXSDInWSDLBehavior and Christian Weyer's FlatWSDL extension. They both work quite well. Possibly too well.

We noticed .NET behaved strangely when referring to a service that had a flattened wsdl.  Everything was a string and all collections were arrays.  Basically, rather than having the luxury of telling the proxy what the underlying data type was and having it handle the appropriate serialization we had to cast everything to and from the underlying on the wire data. It was workable, but in truth it kinda sucked. So, I figured there had to be a way to make WCF emit flat wsdl only when we wanted it.

After spending way too much time chasing down blind alleys I finally decided to just implement a IDispatchMessageInspector as a ServiceBehavior and be done with it. There's probably a nicer, better way to do this, but I haven't found it.

The first thing that needed to be done to make this work was figure out if the request that was about to be sent was in response to a wsdl query.  I didn't find a straight forward way to get that information in BeforeSendReply, so I just grabbed the request URI in the AfterReceiveRequest method and spit it back out as the correlation state object.


   1: public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
   2: {
   3:     //set the uri to the correlation property      
   4:     return request.Properties.Via;
   5: }


Once I had the uri, then I pulled the query string out in BeforeSendReply and if it was a wsdl request (at the standard address) and it specified flat, we can intercept the response and send the flat wsdl instead. While I was in there intercepting things, I thought it would be nice to add a link to the flattened wsdl in the default service description page. So, in the case that a request comes in at the base address with no arguments, then we look and see if the response is the default page and if so, we add our new link to it.


   1: public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
   2: {
   3:     Uri URL = (Uri)correlationState;
   4:     string query = URL.Query;
   5:     string baseaddress = OperationContext.Current.Host.BaseAddresses[0].ToString();
   7:     //is there any possiblity that this is a wsdl request?      
   8:     if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase))
   9:     {
  10:         query = query.Substring(1);
  11:         List<string> queries = new List<string>((query.Length > 0) ? query.Split(new char[] { '&' }) : new string[0]);
  13:         //if it’s a flat wsdl request we need to fix it up        
  14:         if (queries.Contains("wsdl") && queries.Contains("flat"))
  15:         {
  16:             reply = BuildFlatWsdlReply(reply);
  17:         }
  18:     }
  20:     //if they’re just going to the base address, then we need to spruce up the default page      
  21:     else if (URL.ToString().ToLower() == baseaddress.ToLower())
  22:     {
  23:         reply = BuildDescriptionPage(reply, baseaddress);
  24:     }
  25: }


BuildFlatWSDLReply creates a new WsdlExporter, uses it to export the endpoints of the current ServiceHostBase, and sends it along to the methods cribbed from Tomas Restrepo's code for export. Once the wsdl comes back it writes it out to a memory stream and passes it along in a reader to Message.CreateMessage and copies the original method's header and properties to our new and improved message.


   1: private System.ServiceModel.Channels.Message BuildFlatWsdlReply(System.ServiceModel.Channels.Message reply)
   2: {
   3:     //create a wsdl exporter and export the endpoints      
   4:     WsdlExporter exporter = new WsdlExporter();
   5:     ServiceHostBase myHost = OperationContext.Current.Host;
   7:     //creates the wsdl doc      
   8:     exporter.ExportEndpoints(myHost.Description.Endpoints, new System.Xml.XmlQualifiedName(myHost.Description.Name, myHost.Description.Namespace));
   9:     System.ServiceModel.Channels.Message replyMessage = null;
  11:     //write the wsdl as xml to a memory stream      
  12:     MemoryStream meStream = new MemoryStream();
  13:     XmlWriter meXML = XmlWriter.Create(meStream);
  14:     ServiceDescriptionCollection myServices = GetFlatWsdl(exporter);
  15:     myServices[0].Write(meXML);
  16:     meStream.Position = 0;
  18:     //create a reader to pass into the message body      
  19:     XmlReader meRead = XmlReader.Create(meStream);
  20:     replyMessage = System.ServiceModel.Channels.Message.CreateMessage(reply.Version, reply.Headers.Action, meRead);
  22:     //copy everything else from the original message      
  23:     replyMessage.Headers.CopyHeadersFrom(reply.Headers);
  24:     replyMessage.Properties.CopyProperties(reply.Properties);
  25:     reply = replyMessage;
  27:     return reply;
  28: }


The code for building the description page does something similar, but in this case it checks to see if the reply includes the wsdl url and if it finds it, appends the instructions for getting the flattened wsdl if needed. This particular piece of code is ugly, and could benefit from a judicial use of regular expressions. I'm including it here for completeness sake. Don't flame me about it unless you decide to include the code to fix it. ;-)


   1: private static System.ServiceModel.Channels.Message BuildDescriptionPage(System.ServiceModel.Channels.Message reply, string baseaddress)
   2: {
   3:     string body = reply.ToString() + "</HTML>";
   5:     //reply stream omits the closing tag for some reason;     
   6:     string stringToFind = "<A href=\"" + baseaddress + "?wsdl\">" + baseaddress + "?wsdl</A></PRE></P>";
   7:     int foundat = body.IndexOf(stringToFind);
   9:     //if the wsdl string is found, fix up the reply otherwise, just send it back since we can’t deal with it.    
  10:     if (foundat > 0)
  11:     {
  12:         System.ServiceModel.Channels.Message replyMessage = null;
  14:         //modify the standard page and shove it in a string      
  15:         StringBuilder insertText = new StringBuilder();
  16:         insertText.Append("<P class=’intro’>If your client requires a flattened version of the wsdl, it can be retrieved at:");
  17:         insertText.Append("<P><PRE><A href=\"" + baseaddress + "?wsdl&amp;flat\">" + baseaddress + "?wsdl&amp;flat</A></PRE></P></P>");
  18:         string newMessage = body.Insert(foundat + stringToFind.Length, insertText.ToString());
  20:         //create a memory stream and shove our new message into it      
  21:         MemoryStream memStream = new MemoryStream();
  22:         XmlWriter meWrite = XmlWriter.Create(memStream);
  23:         meWrite.WriteRaw(newMessage);
  24:         meWrite.Flush();
  25:         memStream.Position = 0;
  27:         //create a reader for the stream and use it to create the message    
  28:         XmlReader meRead = XmlReader.Create(memStream);
  29:         replyMessage = System.ServiceModel.Channels.Message.CreateMessage(reply.Version, reply.Headers.Action, meRead);
  31:         //copy everything else from the original message       
  32:         replyMessage.Headers.CopyHeadersFrom(reply.Headers);
  33:         replyMessage.Properties.CopyProperties(reply.Properties);
  35:         return replyMessage;
  36:     }
  37:     else
  38:     {
  39:         return reply;
  40:     }
  41: }


That's it in a nutshell. This code is without warranty, either expressed or implied. Hopefully it'll save someone a little bit of pain.


I have posted a .cs file of the code at 

Comments (2) -

  • Shaun

    9/9/2009 8:29:08 AM |

    Great article, but there seems to be a few things missing... for example, where is the GetFlatWsdl() method.  Is it possible for you to post an actual .cs file for this?

  • stever b

    12/11/2009 10:47:58 PM |

    I will be posting a .cs file for this soon.

Comments are closed