Rest Services in WCF

Step 1: Create a new WCF service and write the below code on IService1.cs page.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

namespace RestServices

{

    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.

    [ServiceContract]

    public interface IService1

    {

        [OperationContract]

        [WebInvoke(Method = "GET",

        ResponseFormat = WebMessageFormat.Xml,

        BodyStyle = WebMessageBodyStyle.Wrapped,

        UriTemplate = "xml/{name}")]

        string XMLData(string name);

        [OperationContract]

        [WebInvoke(Method = "GET",

        ResponseFormat = WebMessageFormat.Json,

        BodyStyle = WebMessageBodyStyle.Wrapped,

        UriTemplate = "json/{name}")]

        string JSONData(string name);

    }

 

}

Step 2: Add the below code on Service1.svc,cs page

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

namespace RestServices

{

    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.

    public class Service1 : IService1

    {

        public string XMLData(string name)

        {

            return "You entered the name " + name;

        }

        public string JSONData(string name)

        {

            return "You entered the name " + name;

        }

    }

}

Step 3: Change the web.config file as given below.

<?xml version="1.0"?>

<configuration>

  <system.web>

    <compilation debug="true" />

  </system.web>

  <system.serviceModel>

    <services>

      <service name="RestServices.Service1" behaviorConfiguration="ServiceBehaviour">

        <!-- Service Endpoints -->

        <!-- Unless fully qualified, address is relative to base address supplied above -->

        <endpoint address ="" binding="webHttpBinding" contract="RestServices.IService1" behaviorConfiguration="web">

          <!--

Upon deployment, the following identity element should be removed or replaced to reflect the

identity under which the deployed service runs. If removed, WCF will infer an appropriate identity

automatically.

-->

        </endpoint>

      </service>

    </services>

    <behaviors>

      <serviceBehaviors>

        <behavior name="ServiceBehaviour">

          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->

          <serviceMetadata httpGetEnabled="true"/>

          <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->

          <serviceDebug includeExceptionDetailInFaults="false"/>

        </behavior>

      </serviceBehaviors>

      <endpointBehaviors>

        <behavior name="web">

          <webHttp/>

        </behavior>

      </endpointBehaviors>

    </behaviors>

    <serviceHostingEnvironment/>

  </system.serviceModel>

  <system.webServer>

    <modules runAllManagedModulesForAllRequests="true"/>

  </system.webServer>

</configuration>

 
Step4: Run your application and test like below from web-browser.

http://localhost:5017/Service1.svc/xml/Pankaj
http://localhost:5017/Service1.svc/json/Pankaj

Now you can call it from your application also.

just add this code in your application.

HttpWebRequest request =

(HttpWebRequest)HttpWebRequest.Create(

@"http://localhost:5017/Service1.svc/xml/12345");

request.Accept = "*/*";

// we're going to post JSON

request.ContentType = "application/json";

request.Method = "GET";

// get the response

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

using (Stream stream = response.GetResponseStream())

{

using (TextReader reader = new StreamReader(stream))

{

Console.WriteLine(reader.ReadToEnd().Substring(60).Replace("</XMLDataResult></XMLDataResponse>","")+" xml");

}

}

Ebook Download
View all
Learn
View all