用VS 2008开发WCF(一)——最快速的WCF入门

第一步,打开VS 2008,然后新建一个项目,项目使用WCF类型,具体选择“WCF类库”。

什么都不用改,直接设置新建好了的WCF类库项目为启动项目,Ctrl+F5开始运行。

什么?类库不能直接运行?你且试试。

系统托盘会出现一个WCF服务主机的小图标,点击,查看这个WCF项目被分配为什么访问路径。

这样我们就新建好了一个WCF服务,其中的代码应该是默认的。

 

IService1.cs

using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace WcfServiceLibrary { // 注意: 如果更改此处的接口名称“IService1”,也必须更新 App.config 中对“IService1”的引用。 [ServiceContract] public interface IService1 { [OperationContract] string GetData(int value); [OperationContract] CompositeType GetDataUsingDataContract(CompositeType composite); // 任务: 在此处添加服务操作 } // 使用下面示例中说明的数据协定将复合类型添加到服务操作 [DataContract] public class CompositeType { bool boolValue = true; string stringValue = "Hello "; [DataMember] public bool BoolValue { get { return boolValue; } set { boolValue = value; } } [DataMember] public string StringValue { get { return stringValue; } set { stringValue = value; } } } }

 

Service1.cs

using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace WcfServiceLibrary { // 注意: 如果更改此处的类名“IService1”,也必须更新 App.config 中对“IService1”的引用。 public class Service1 : IService1 { public string GetData(int value) { return string.Format("You entered: {0}", value); } public CompositeType GetDataUsingDataContract(CompositeType composite) { if (composite.BoolValue) { composite.StringValue += "Suffix"; } return composite; } } }

 

App.config

 

下面我们新建一个WindowsConsole项目(方便而已,你完全可以新建一个其它的,只要能输出结果就行)

在项目上右击,添加服务引用。

注:必须最低是.NET 3.0项目才会出现此选项,如果发现没有,请查看是否该项目创建版本低于3.0了

服务引用的地址就是刚才系统默认分配的地址

添加完成后,在代码中调用下面的代码,即可看到调用成功了

IService1 serv = new Service1Client(); Console.WriteLine(serv.GetData(2));

 

根本不需要特意写一个HOST,因为VS已经提供WCF的服务主机了。

先跨进WCF的门槛,然后再慢慢研究如果托管,不是更好吗。

转载于:https://www.cnblogs.com/vanpan/archive/2009/02/11/3583045.html

你可能感兴趣的:(用VS 2008开发WCF(一)——最快速的WCF入门)