WCF Rest Services for Windows Phone

1 minute read

So great, to create WCF Rest services for Windows Phone, you have to follow just 5 steps.  This post will have more code than words, making it neat and to-the-point

Step 1: Create a WCF Service

Define the interface IMyService in 'Services' folder of YourWebsite

namespace YourWebsite.Services
       [ServiceContract(Namespace = "http://YourWebsite.com/services", Name = "MyService")]
       public interface IMyService
         [WebGet(UriTemplate = "?nm={name}",  RequestFormat = WebMessageFormat.Xml, 
                ResponseFormat = WebMessageFormat.Xml,
                BodyStyle = WebMessageBodyStyle.Bare)]

         bool DoWork(string name);

Add a service MyService.svc that inherits from IMyService

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
      public bool DoWork(string name)
         return true;

Step 2: Modify the markup of MyService.svc

The markup of the MyService.svc should have

<%@ ServiceHost Language="C#" Debug="true" Service="YourWebsite.Services.MyService"
CodeBehind="MyService.svc.cs" >

Step 3: Modify Web.Config of the Hosting Website

Add REST behavior (webHttp) to web.config

      <add prefix="http://www.YourWebsite.com/Services"/>
      <behavior name="restBehavior">
        <webHttp />
      <behavior name="">
        <serviceMetadata httpGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="false" />

  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <endpoint address="MyService.svc" binding="webHttpBinding" contract="YourWebsite.Services.IMyService" behaviorConfiguration="restBehavior" />



Step 4: Calling MyService in Windows Phone

We don't need to create any proxy class, and a simple WebClient can do the proxy stuff for us!

string url = string.Format("http://yourwebsite.com/services/MyService.svc?nm={0}", "My Name");
WebClient proxy = new WebClient();
proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(proxy_OpenReadCompleted);
proxy.OpenReadAsync(new Uri(url, UriKind.Absolute));

Once the WCF service is invoked, proxy_OpenReadCompleted is called.

private void proxy_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
      if (e.Error != null)
          // do something

      DataContractSerializer serializer = new DataContractSerializer(typeof(bool));
      bool returnValue = (bool)serializer.ReadObject(e.Result);


Step 5: Execute

And you are done!  Just execute your Windows Phone application and you will have the RESTed output :)