WCF+restful

服务端代码:hosting方式

View Code
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace Hosting
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ServiceHost host = new ServiceHost(typeof(AccountService)))
            {
                host.Open();
                Console.WriteLine("AccountService Address:");
                foreach (var endpoint in host.Description.Endpoints)
                {
                    Console.WriteLine(endpoint.Address.ToString());
                }
                Console.WriteLine("AccountService Started,Press any key to stop service...");
                Console.ReadKey();
                host.Close();
            }
        }
    }

    [ServiceContract]
    public interface IAccountJsonService
    {
        [OperationContract(Name = "GetAccountDataJson")]
        [WebInvoke(Method = "*", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetAccountData", BodyStyle = WebMessageBodyStyle.Bare)]
        List<Account> GetAccountData();

        [OperationContract(Name = "SendMessageJson")]
        [WebInvoke(Method = "get", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "SendMessage")] // UriTemplate = "SendMessage/?Message={Message}"
        string SendMessage(string Message);

        [OperationContract(Name = "SendMessage2Json")]
        [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "SendMessage2")]
        string SendMessage2(ReqData data);

        [OperationContract(Name = "GetMessageDataJson")]
        [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "GetMessageData", BodyStyle = WebMessageBodyStyle.Bare)]
        ReqData GetMessageData();
    }

    [ServiceContract]
    public interface IAccountXmlService
    {
        [OperationContract(Name = "GetAccountDataXml")]
        [WebGet(RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "GetAccountData", BodyStyle = WebMessageBodyStyle.Bare)]
        List<Account> GetAccountData();

        [OperationContract(Name = "SendMessageXml")]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, UriTemplate = "SendMessage/{Message}", BodyStyle = WebMessageBodyStyle.Bare)]
        string SendMessage(string Message);
    }


    public class AccountService : IAccountJsonService, IAccountXmlService
    {
        public List<Account> GetAccountData()
        {
            return MockAccount.AccountList;
        }
        public string SendMessage(string Message)
        {
            return " Message:" + Message;
        }

        public string SendMessage2(ReqData data)
        {
            return data.Message + "message";
        }

        public ReqData GetMessageData()
        {
            return new ReqData() { Message = "feww" };
        }

    }
    [DataContract]
    public class ReqData
    {
        [DataMember]
        public string Message { get; set; }
    }

    [DataContract]
    public class Account
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public int Age { get; set; }
        [DataMember]
        public string Address { get; set; }
        [DataMember]
        public DateTime Birthday { get; set; }
    }

    public class MockAccount
    {
        public static List<Account> AccountList
        {
            get
            {
                var list = new List<Account>();
                list.Add(new Account { Name = "Bill Gates", Address = "YouYi East Road", Age = 56, Birthday = DateTime.Now });
                list.Add(new Account { Name = "Steve Paul Jobs", Address = "YouYi West Road", Age = 57, Birthday = DateTime.Now });
                list.Add(new Account { Name = "John D. Rockefeller", Address = "YouYi North Road", Age = 65, Birthday = DateTime.Now });
                return list;
            }
        }
    }
}

配置文件:app.config

<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <!--<serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetUrl="mex" httpGetEnabled="true"/>
          <serviceDebug httpHelpPageEnabled="true" includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>-->
      <endpointBehaviors>
        <behavior name="WebHttpBindingBehavior">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>

    <services>
      <service name="Hosting.AccountService">
        <!--<endpoint address="xml" binding="webHttpBinding"  contract="Hosting.IAccountXmlService" behaviorConfiguration="WebHttpBindingBehavior"/>-->
        <endpoint address="" binding="webHttpBinding"  contract="Hosting.IAccountJsonService" behaviorConfiguration="WebHttpBindingBehavior"/>
        <host>
          <baseAddresses>
            <add baseAddress="http://127.0.0.1:82/AccountService" />
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>
</configuration>

 客户端调用:利用webClient和httpWebRequest、HttpWebResponse请求数据

View Code
WebClient cli = new WebClient();
            string json = cli.DownloadString(new Uri("http://127.0.0.1:82/AccountService/GetAccountData"));


            string strjson = "{\"Message\":\"feww\"}";
            byte[] bytes = Encoding.ASCII.GetBytes(strjson);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("http://127.0.0.1:82/AccountService/SendMessage2"));
            request.Method = "POST";
            request.ContentType = "application/json";//"application/x-www-form-urlencoded";//"application/json";//
            request.ContentLength = bytes.Length;
            using (Stream rstream = request.GetRequestStream())
            {
                rstream.Write(bytes, 0, bytes.Length);
            }
            HttpWebResponse res = (HttpWebResponse)request.GetResponse();

            string strresult = "";
            Stream receivestream = res.GetResponseStream();
            Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
            StreamReader sr = new StreamReader(receivestream, encode);
            char[] read = new char[256];
            int count = sr.Read(read, 0, 256);
            while (count > 0)
            {
                string str = new string(read, 0, count);
                strresult += str;
                count = sr.Read(read, 0, 256);
            }

 

 

posted @ 2012-09-27 14:18  老牛在路上  阅读(360)  评论(0)    收藏  举报