use webHttpBinding to implement WCF Rest Service


Comparison between webHttpBinding, basicHttpBinding and wsHttpBinding

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app

Source Code:

  1. Program.cs
  2. IService.cs
  3. Service.cs
  4. app.config
1. Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WCFLearning2
{
    class Program
    {
        static void Main(string[] args)
        {
            using (System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(WCFLearning2.Service)))
            {
                host.Open();
                Console.WriteLine("Service started. press any key to stop it");
                Console.ReadLine();
                host.Close();
            }
        }
    }
}

2. IService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace WCFLearning2
{
    [ServiceContract]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(Method = "GET",
         ResponseFormat = WebMessageFormat.Json,
         UriTemplate = "users/{value}")]
        string GetData(string value);

        [OperationContract]
        [WebInvoke(Method = "POST",
         BodyStyle = WebMessageBodyStyle.Wrapped,
         ResponseFormat = WebMessageFormat.Json)]
        string[] GetUser(string Id);
    }
}

3.Service.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WCFLearning2
{
    public class Service : IService
    {
        public string GetData(string value)
        {
            Console.WriteLine("You entered: {0}", value);
            return string.Format("You entered: {0}", value);
        }


        public string[] GetUser(string Id)
        {
            return new User().GetUser(Convert.ToInt32(Id));
        }
    }

    public class User
    {

        Dictionary<int, string> users = null;
        public User()
        {
            users = new Dictionary<int, string>();
            users.Add(1, "pranay");
            users.Add(2, "Krunal");
            users.Add(3, "Aditya");
            users.Add(4, "Samir");
        }

        public string[] GetUser(int Id)
        {
            var user = from u in users
                       where u.Key == Id
                       select u.Value;

            return user.ToArray<string>();
        }

    }
}

4. app.config
<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="WCFLearning2.Service" 
               behaviorConfiguration="WcfServiceLibrary.Service1Behavior">
        <host>
          <baseAddresses>
            <add baseAddress = "http://localhost:8080/Service1/" />
          </baseAddresses>
        </host>
        <!-- Service Endpoints -->
        <!-- Unless fully qualified, address is relative to base address supplied above -->
        <!--<endpoint address="net.tcp://localhost:9000/myservice" binding="netTcpBinding" contract="WcfServiceLibrary.IService1">-->

        <!--</endpoint>-->
        <endpoint 
          address ="" 
          binding="webHttpBinding"
          contract="WCFLearning2.IService"
          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.
          -->
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <!-- Metadata Endpoints -->
        <!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
        <!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfServiceLibrary.Service1Behavior">
          <!-- 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>

  </system.serviceModel>
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/></startup></configuration>

Result:


"You entered: good"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值