创建基本 WCF 服务时,第一项任务是定义协定。协定指定服务支持的操作。可以将操作视为一个 Web 服务方法。通过定义 C++、C# 或 VB 接口可创建协定。接口中的每个方法都对应于特定的服务操作。每个接口都必须将 ServiceContractAttribute 应用于自身,而每个操作都必须将 OperationContractAttribute 应用于自身。如果接口中的一个方法具有 ServiceContractAttribute 而没有 OperationContractAttribute,则不公开该方法。
使用接口创建 Windows Communication Foundation 协定
1、 打开Visual Studio 2008,创建新的控制台应用程序项目。 在“新建项目”对话框中,选中“Visual C#”,并选择“控制台应用程序”模板,并命名为 Service。 使用默认的位置。 将默认的 Service 命名空间更改为 ServiceModel.Samples。 为项目提供对 System.ServiceModel 命名空间的引用:右击“解决方案资源管理器”中的“Service”项目,从“.NET”选项卡中的“组件名称”中选择“System.ServiceModel”,然后单击“确定”。
2、为 System.ServiceModel 命名空间添加一个 using 语句。
using System.ServiceModel;
3、创建一个新的 ICalculator 接口类文件,并将 ServiceContractAttribute 属性应用于该接口,并将 Namespace 值设置为“[url]http://ServiceModel.Samples[/url]”(这个可以添加也可不添加)。 此命名空间指定该服务在计算机上的路径,并构成该服务的基址部分。 请注意,在通过采用方括号表示法的属性来批注接口或类时,该属性类可以从其名称中去掉“Attribute”部分。
[ServiceContract(Namespace = "
[url]http://ServiceModel.Samples[/url]")]
public interface ICalculator
public interface ICalculator
4、在接口中创建方法声明,并将 OperationContractAttribute 属性应用于每个要作为公共 WCF 协定的一部分公开的方法。
[OperationContract]
double Add(double n1, double n2);
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
至此服务协定就完成了,创建服务协定后,创建 WCF 服务的下一步是实现服务协定。详情请见下一篇《构建高性能分布式搜索引擎(Wcf-示例篇)三之实现WCF服务协定》.
如果有需要可以下载附件示例项目作参考!
深圳E搜科技(搜索引擎技术钻研者!)
QQ群:15911745
QQ:448114915;934724029
Mobile:13168078506;13713628016
Email:pc2004lcq@126.com;jackbison@163.com
深圳E搜科技(搜索引擎技术钻研者!)
QQ群:15911745
QQ:448114915;934724029
Mobile:13168078506;13713628016
Email:pc2004lcq@126.com;jackbison@163.com
转载于:https://blog.51cto.com/desertwolf/131504