参考:http://www.cnblogs.com/huangxincheng/p/4558747.html 十五天精通WCF——第一天 三种Binding让你KO80%的业务
理论:WCF的通讯方式基于HTTP协议,传输消息为soap
1、接口
第一步需要定义一个接口
并不知道不定义该接口是否可行,接口既然是作为一种行为规范,所以不定义应该也是可行的
注意:一定要引入 System.ServiceModel;
1 using System.Runtime.Serialization; 2 using System.ServiceModel; 3 4 namespace MyService 5 { 6 [ServiceContract] //只是接口或类在应用程序中定义的服务协议 ——可以理解为该标记将类或接口设置为服务协议 7 public interface IHomeService 8 { 9 [OperationContract] //指定方法定义一个操作,该操作是该协议的一部分 ——该标记将该方法定义为协议中必须实现的 10 int GetLength(string name); 11 } 12 }
2、实现类
有接口就一定会有实现该接口的类
注意:引用 System.Messaging; System.Threading;
1 using System; 2 using System.Messaging; 3 using System.Threading; 4 5 namespace MyService 6 { 7 public class HomeService : IHomeService 8 { 9 public int GetLength(string name) 10 { 11 return name.Length; 12 } 13 } 14 }
3、启动服务
到这一步,WCF可以说基本配置成型,但还不能被外部程序调用
目前你可以在WCF中添加一个Form.cs调用之前实现的方法,也可按找参考文章中的做法
具体看需求
4、配置config文件
完成这一步,WCF将可以被外部程序调用
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <bindings> <netTcpBinding> <binding name="IHomeServiceBinding" /> </netTcpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name=""> <serviceMetadata httpGetEnabled="true" httpGetUrl="WCF链接地址" /> <!--设置可以被远程调用--> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> <services> <service name="MyService.HomeService"> <endpoint address="http://127.0.0.1:1920/HomeService" binding="basicHttpBinding" contract="MyService.IHomeService"> <identity> <dns value="localhost" /> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> <host> <baseAddresses> <add baseAddress="http://127.0.0.1:1920"/> </baseAddresses> </host> </service> </services> </system.serviceModel> </configuration>
5、通过WindowForm添加服务引用调用WCF
VS中与添加Web Service操作相同。添加成功后将会在App.config中自动配置节点。