Sunday, 31 July 2011

WCF Example: Simple example for RESTful type


Below Example describes how to create and access WCF RESTful type service and hosted in IIS.
Also example shows JSON type data.
Create a WCFService Project in Visual Studio
Ex: WcfTest
1.       Write the following code in IService1.cs

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace WcfTest
{
    // NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/GetNameById?id={id}")]
        string GetNameById(string id);

        [OperationContract]
        [WebGet(
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/GetCompany")]
        string GetCompany();

        [OperationContract]
        [WebGet(
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/")]
        string TestMethod();



        [OperationContract]
        [WebGet(
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json)]
        List<Employee> GetEmployees();
    }

    [DataContract]
    public class Company
    {
        string compName = "Company Name";
        string location = "Bangalore";

        [DataMember]
        public string CompName
        {
            get { return compName; }
            set { compName = value; }
        }

        [DataMember]
        public string Location
        {
            get { return location; }
            set { location = value; }
        }

        [DataMember]
        public string CompanyAddress
        {
            get { return (CompName + " " + Location); }
        }
    }



    [DataContract]
    public class Employee
    {
        string firstName = string.Empty;
        string secondName = string.Empty;
        string address = string.Empty;

        [DataMember]
        public string FirstName
        {
            get { return firstName; }
            set { firstName = value; }
        }

        [DataMember]
        public string SecondName
        {
            get { return secondName; }
            set { secondName = value; }
        }

        [DataMember]
        public string Address
        {
            get { return address; }
            set { address = value; }
        }
    }
}


1.       Write the following code in Service1.svc.cs file
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using System.ServiceModel;

namespace WcfTest
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
    public class Service1 : IService1
    {

        #region IService1 Members

        public string GetNameById(string id)
        {
            return "hello " + id;
        }

        public string GetCompany()
        {
            Company comp = new Company();

            StringBuilder sbJson = new StringBuilder();
            new JavaScriptSerializer().Serialize(comp, sbJson);

            return sbJson.ToString();
        }

        public string TestMethod()
        {
           return "Company, Bangalore, India";
        }


        public List<Employee> GetEmployees()
        {
            List<Employee> employeesList = new List<Employee>();

            Employee employee = null;
           
            employee = new Employee();
            employee.FirstName = "Sharath";
            employee.SecondName = "Kumar";
            employee.Address = "Bangalore";
            employeesList.Add(employee);

            employee = new Employee();
            employee.FirstName = "Employee2First";
            employee.SecondName = "Employee2Second";
            employee.Address = "Bangalore, Jayanagar";
            employeesList.Add(employee);

            return employeesList;
        }
        #endregion


    }
}

1.       Verify this entry in Service1.svc
<%@ ServiceHost Language="C#" Debug="true" Service="WcfTest.Service1" CodeBehind="Service1.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

2.  Write the the following in web.config in Service model

  <system.serviceModel>
   <!--http://localhost/WCFTest/Service1.svc-->
    <services>
      <service name="WcfTest.Service1" behaviorConfiguration="WcfTest.Service1Behavior">
        <endpoint address="" behaviorConfiguration="web"
                  binding="webHttpBinding”
                  contract="WcfTest.IService1">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfTest.Service1Behavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="web">
          <webHttp />
        </behavior>
        <behavior name="web2">
          <webHttp />
        </behavior>
      </endpointBehaviors>
    </behaviors>

</system.serviceModel>

3.       Publish the application and Host the in IIS (Add Ppplication in DefaultApplication and give the Published path in Physical Path)
4.       Try accessing the following URL

Result: "Company, Bangalore, India"
 
http://localhost/WCFTest/Service1.svc/GetNameById?id=200
Result: "hello 200"
 
http://localhost/WCFTest/Service1.svc/GetCompany
Result (Object in JSON format): "{\"CompName\":\"Company Name\",\"Location\":\"Bangalore\",\"CompanyAddress\":\"Company Name Bangalore\"}"


http://localhost/WCFTest/Service1.svc/GetEmployees
Result:
[{"Address":"Bangalore","FirstName":"Sharath","SecondName":"Kumar"},{"Address":"Bangalore, Jayanagar","FirstName":"Employee2First","SecondName":"Employee2Second"}]

Thanks,
Sharath




No comments:

Post a Comment