我们来写一个WCF的HelloWorld来增加对WCF的认识。
一、创建解决方案
首先创建如下的工程,建立一个解决方案,添加Client、Service、和Host的Console Application。如下图:
该实例主要实现1、WCF服务端。2、WCF客户端。3、WCF的宿主环境,如下图:
二、编写WCF服务端程序
现在我们开始写WCF服务端程序了,首先添加System.ServiceModel引用。然后编写下面的代码:
IGetDataService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
6:
namespace Service
8: {
//定义契约
10: [ServiceContract]
interface IGetDataService
12: {
13: [OperationContract]
string GetData();
15: }
16: }
GetDataService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
5:
namespace Service
7: {
class GetDataService : IGetDataService
9: {
string GetData()
11: {
;
13: }
14: }
15: }
OK,服务端代码已经编写完毕。但是WCF服务如果要想运行的话,必须有一个宿主环境(Host)如下图,现在我们来实现这个宿主环境。
三、实现WCF宿主环境,并启动WCF服务。
添加System.ServiceModel引用后,宿主环境代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using Service;
8:
namespace Host
10: {
class Program
12: {
string[] args)
14: {
//定义ServiceHost
typeof(GetDataService));
//添加终结点
);
//查找元数据
20: ServiceMetadataBehavior behavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
null)
22: {
new ServiceMetadataBehavior();
true;
);
26: host.Description.Behaviors.Add(behavior);
27: }
else
29: {
true;
31: }
32:
//注册一个事件,当服务开启的时候打印出服务开始
delegate
35: {
);
37: };
38:
//开启服务
40: host.Open();
41: Console.ReadKey();
42: }
43: }
44: }
运行宿主环境,启动服务。在浏览器中输入:http://localhost:8818/getData/metadata,如果获取到了元数据,则证明服务宿主编写成功。如下图:
四、实现客户端,并访问WCF服务。
首先添加服务引用,Reference ----Add Service Reference 按下图添加:点击OK后VS会为我们生成客户端的访问代码,我们调用即可。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
5:
namespace Client
7: {
class Program
9: {
string[] args)
11: {
//调用客户端生成的代码
new GetDataServiceClient();
14: Console.Write(client.GetData());
15: Console.ReadKey();
16: }
17: }
class GetDataServiceClient : System.ServiceModel.ClientBase<Client.GetDataService.IGetDataService>, Client.GetDataService.IGetDataService
19: {
20:
public GetDataServiceClient()
22: {
23: }
24:
string endpointConfigurationName) :
base(endpointConfigurationName)
27: {
28: }
29:
string remoteAddress) :
base(endpointConfigurationName, remoteAddress)
32: {
33: }
34:
string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress)
37: {
38: }
39:
public GetDataServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress)
42: {
43: }
44:
string GetData()
46: {
base.Channel.GetData();
48: }
49: }
50: }