代码改变世界

Android访问WCF服务(上篇)-服务端开发

2011-02-24 17:45  Vincent.C  阅读(9796)  评论(4编辑  收藏  举报

本章目的: 用Wcf建立可以上Android可以访问的数据服务, 数据传输格式采用比较适合于移动互联网传输的Json格式.

服务的开发流程我们按照 服务契约(ServiceContract), 服务实现(Service), 实体对象模型(Model) 及服务发布的流程来介绍.

由于自己对Http请求的链接认识的比较浅,对于有些问题没法做出清楚明了的解释, Android访问WCF这篇文章我会贴出来代码, 让后说明一下关注的地方, 不做深入研究.

一. 服务契约(Contract)

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

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

此契约定义了两个方法, GetAccountData(获取Account数据列表, 方法不带参数), SendMessage, 获取从客户端传过来的数据, 并返回;

1. 这里面注意WebInvoke(SendMessage方法)这个Attribute, Method代表了Http的访问方法, 我们这是从服务器获取数据,是请求数据, 所以用GET, 这个也可以用另外一个Attribute来替代-WebGet(GetAccountData方法);

2. 我们要给客户端返回Json数据,我们只需在WebInvoke or WebGet Attribute中指定ResponseFormat的格式即可, 这个从名字命名就可以看出来是制定返回的数据格式的.

3. 要注意UriTemplate属性, 这个是指定我们请求时的方法路径, 后面给出示例.

二. 服务实现(Service)

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

此处只是实现了IAccountJsonService接口.

三. 实体对象模型&模拟数据

实体类定义:
[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;
           }
       }
   }

模拟数据返回一个Account的列表, 含有三条模拟数据, Birthday用DateTime.Now可是随时查看数据是不是最新生成的.

 

四. 服务发布

在这个例子里面, 我们的服务采用Console的发布形式, 如果采用IIS发布, 只要参考WCF的服务配置信息, 在IIS环境下配置就OK了.

WCF配置信息

  <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="json" binding="webHttpBinding"  contract="Hosting.IAccountJsonService" behaviorConfiguration="WebHttpBindingBehavior"/>-->
        <host>
          <baseAddresses>
            <add baseAddress="http://127.0.0.1:82/AccountService"/>
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel>

控制台进行服务的托管发布

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();
           }
       }
   }

下篇将介绍Android如何访问我们编写的服务.

示例代码下载