WCF: Consuming Xml Rest Service

Below is an example of how to consume a restful service that returns xml date from wcf client. This example is based on a discography service that returns releases for a specific artist. The name of the artist is passed in the query string.

Example xml returned by service:

  <Name>Example Artist</Name>
  <Genre>Example Genre</Genre>
      <Title>Track 1</Title>
      <Title>Track 2</Title>

To consume this, first declare the bindings and endpoints in the appropriate app.config / web.config

<?xml version=”1.0″ encoding=”utf-8″ ?>
        <binding name=”ArtistBinding” maxReceivedMessageSize=”65536″>
          <!– Security is integrated auth –>
          <security mode=”TransportCredentialOnly”>
            <transport clientCredentialType=”Windows” />
      <endpoint address=”
          binding=”webHttpBinding” bindingConfiguration=”ArtistBinding”
          name=”ArtistService” />

Define the contract using the the WebGet attribute. Note the way the artist name is passed through on the query string (ideally a restful service will rely on nouns as opposed to query string verbs), Also note that the type “Artist” is defined later.

using System.ServiceModel;
using System.ServiceModel.Web;

namespace RestWcfClient
    public interface IArtist

            BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml,
            UriTemplate = “RestServiceForWcfExample/Discog.ashx?artist={artistName}”)]
        Artist GetDiscography(string artistName);

To consume from the method define in the template, use the following code in your client:

// “ArtistService” refers to the named endpoint in the web.config / app.config
using (var cf = new WebChannelFactory<IArtist>(“ArtistService”))
        var s = cf.CreateChannel();
        var result = s.GetDiscography(“An artist”);
    catch (Exception e)

The data types used in this example are shown below (these need only to exist in the client). Note that the name of types should match the name of the xml elements returned from the rest service.

[XmlType(AnonymousType = true, Namespace = “”)]
[XmlRoot(Namespace = “”, IsNullable = false)]
public class Artist
    public string Name { get; set; }
    public string Genre { get; set; }
    public List<Track> Tracks { get; set; }

public class Track
    public string Title { get; set; }
    public DateTime Released { get; set; }

You May Also Like

About the Author: rnowik

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.