1.创建服务器端解决方案,创建三个项目如下图:
1.1DataModel类库使用ADO.NET实体框架集做数据库映射
1.2Services类库用来存放服务,代码如下:
接口:
/// <summary>
/// 服务契约
/// </summary>
[ServiceContract]
public interface IDataServices
{
/// <summary>
/// 操作契约,此标记表示将该方法公布给客户端调用
/// </summary>
/// <returns></returns>
[OperationContract]
List<Products> GetProductsList();
}
实现类:
public class DataServices : IDataServices
{
NorthwindEntities dbContext = null;
public DataServices()
{
dbContext = new NorthwindEntities();
}
#region IDataServices 成员
public List<Products> GetProductsList()
{
return dbContext.Products.ToList();
}
#endregion
}
1.3.1创建宿主
//创建宿主对象,用于承载服务;typeof里面是接口的实现类,就是那个契约 这个是手动写代码创建宿主
using (ServiceHost host = new ServiceHost(typeof(DataServices)))
{
//公布一个终结点,以便客户端请求服务
//第一个参数是这个节点要提供的契约
//第二个参数绑定的是传输消息的方式
//第三个参数是服务所在的位置
host.AddServiceEndpoint(typeof(IDataServices), new NetTcpBinding(), "net.tcp://localhost:8000/DataServices");
host.Open();
Console.WriteLine("服务端开始监听!");
Console.ReadKey();
}
1.3.2 通过配置文件设置宿主(推荐使用方式,因为若是要改传输协议,可以避免修改代码)
<configuration>
<connectionStrings>
<add name="NorthwindEntities" connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa;Password=123;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
<system.serviceModel>
<!--这个节使用来配置服务-->
<services>
<!--这个Name是必须的,它指定了具体提供服务的类;behaviorConfiguration设置行为配置策略-->
<service name="Services.DataServices" behaviorConfiguration="serviceBehavior">
<!--使用http协议绑定;绑定具体的服务协议;设置服务地址,这个地址是个相对baseAddress的地址-->
<endpoint binding="basicHttpBinding" contract="Services.IDataServices" address="DataServices"></endpoint>
<!--这是元数据交换特有的绑定协议;IMetadataExchange元数据交换协定-->
<endpoint binding="mexHttpBinding" contract="IMetadataExchange" address="mex"></endpoint>
<!--这个节配置宿主信息-->
<host>
<baseAddresses>
<add baseAddress="http://localhost:6540"/>
</baseAddresses>
</host>
</service>
</services>
<!--这个节使用来配置服务的行为-->
<behaviors>
<serviceBehaviors>
<behavior name="serviceBehavior">
<!--指定元数据使用http的get方式获取-->
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
2创建客户端解决方案
对于1.3.1中的创建宿主的方式,客户端使用如下方法调用服务:
public class WCFClient
{
IDataServices proxy;
public WCFClient()
{
//这个泛型指定这个代理遵循那个契约,创建客户端代理以调用服务
proxy = ChannelFactory<IDataServices>.CreateChannel(new NetTcpBinding(), new EndpointAddress("net.Tcp://localhost:8000/DataServices"));
}
public List<Products> GetProductsList()
{
//return proxy.GetProductsList();
DataServicesClient client=new DataServicesClient();
//注意:通过工具引用服务的方式,把列表传回来时生成的是数组,所以要转成List
return client.GetProductsList().ToList();
//return null;
}
}
/// <summary>
/// 构建服务契约的副本;此接口告知客户端,服务端提供什么服务
/// </summary>
[ServiceContract]
public interface IDataServices
{
[OperationContract]
List<Products> GetProductsList();
}
对于1.3.2中的创建宿主的方式,客户端使用如下方法调用服务:注意注释的部分:原因是一个服务不能同时使用两个绑定协议.引用服务的方式就是右键---添加服务引用就OK.
注意:这个system.serviceModel节需要放到web.config里面去,不然报以下错误:
在 ServiceModel 客户端配置部分中,找不到引用协定“ServiceReference1.IDataServices”的默认终结点元素。这可能是因为未找到应用程序的配置文件,或者是因为客户端元素中找不到与此协定匹配的终结点元素
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IDataServices" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize="65536000" maxBufferPoolSize="524288" maxReceivedMessageSize="65536000"
messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
<!--<netTcpBinding>
<binding name="NetTcpBinding_IDataServices" closeTimeout="00:01:00"
openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
transactionFlow="false" transferMode="Buffered" transactionProtocol="OleTransactions"
hostNameComparisonMode="StrongWildcard" listenBacklog="10"
maxBufferPoolSize="524288" maxBufferSize="65536" maxConnections="10"
maxReceivedMessageSize="65536">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<reliableSession ordered="true" inactivityTimeout="00:10:00"
enabled="false" />
<security mode="Transport">
<transport clientCredentialType="Windows" protectionLevel="EncryptAndSign" />
<message clientCredentialType="Windows" />
</security>
</binding>
</netTcpBinding>-->
</bindings>
<client>
<endpoint address="http://localhost:6540/DataServices" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IDataServices" contract="ServiceReference1.IDataServices"
name="BasicHttpBinding_IDataServices" />
<!--<endpoint address="net.tcp://localhost:8000/DataServices" binding="netTcpBinding"
bindingConfiguration="NetTcpBinding_IDataServices" contract="ServiceReference1.IDataServices"
name="NetTcpBinding_IDataServices">
<identity>
<userPrincipalName value="OI7CXRCNM6CGSIS\Administrator" />
</identity>
</endpoint>-->
</client>
</system.serviceModel>
</configuration>
项目代码下载:http://download.youkuaiyun.com/detail/yoyoshaoye/3611523