自托管WCF服务
2011-08-01 13:36 雪中风筝 阅读(287) 评论(0) 编辑 收藏 举报声明WCF服务并且声明客户端提供的操作
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.ServiceModel;
6 using System.ServiceModel.Description;
7
8 namespace SelfHost
9 {
10 [ServiceContract]
11 interface IHelloWorld
12 {
13 [OperationContract]
14 string SayHello(string name);
15 }
16 }
实现服务
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace SelfHost
7 {
8 class HelloWorldService : IHelloWorld
9 {
10 public string SayHello(string name)
11 {
12 return string.Format("Hello,{0}", name);
13 }
14 }
15 }
运行服务的主进程
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.ServiceModel;
6 using System.ServiceModel.Description;
7
8 namespace SelfHost
9 {
10 class Program
11 {
12 static void Main(string[] args)
13 {
14 Uri baseAddress = new Uri("http://localhost:8080/hello");
15
16 using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
17 {
18 //添加终结点
19 host.AddServiceEndpoint(typeof(IHelloWorld), new WSHttpBinding(), baseAddress);
20
21 //获取元数据
22 ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
23 smb.HttpGetEnabled = true;
24 smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
25
26 host.Description.Behaviors.Add(smb);
27
28 host.Open();
29
30 Console.WriteLine("The Service is already at {0}", baseAddress);
31 Console.WriteLine("Press <Enter> to stop the service");
32
33 Console.ReadLine();
34
35 host.Close();
36 }
37
38
39 }
40 }
41 }
CTL+F5运行
运行WCFTESTCLIENT.exe进行测试
这种方式就是WCF的自托管。