超简单WCF例子

项目图如下:

 1 using System;
 2 using System.ServiceModel;
 3 
 4 namespace ServiceLib
 5 {
 6     [ServiceContract]
 7     public interface ICalcService
 8     {
 9         /// <summary>
10         /// 欢迎方法
11         /// </summary>
12         /// <param name="name"></param>
13         /// <returns></returns>
14         [OperationContract]
15         String WelCome(String name);
16     }
17 }
ICalcService
 1 using System;
 2 
 3 namespace ServiceLib
 4 {
 5     public class CalcService:ICalcService
 6     {
 7         /// <summary>
 8         /// 欢迎
 9         /// </summary>
10         /// <param name="name"></param>
11         /// <returns></returns>
12         public string WelCome(string name)
13         {
14             Console.WriteLine(name);
15             return "你好:" + name;
16         }
17     }
18 }
CalcService
 1 using System;
 2 using System.ServiceModel;
 3 using System.ServiceModel.Description;
 4 
 5 using ServiceLib;
 6 
 7 namespace CalcHost
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             // 指定契约
14             Uri address = new Uri("http://127.0.0.1:8888");
15             ServiceHost host = new ServiceHost(typeof(CalcService),address);
16             host.AddServiceEndpoint(typeof(ICalcService), new WSHttpBinding(), "Calc");
17 
18             // 公开元数据    注:这个上线前关掉应该比较好
19             ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
20             smb.HttpGetEnabled = true;
21             host.Description.Behaviors.Add(smb);
22 
23             // 开启服务
24             host.Opened += (a, b) => Console.WriteLine("服务已开启");
25             host.Open();
26             Console.Read();
27         }
28     }
29 }
CalcHost.Program
 1 using Client.ServiceReference;
 2 using System;
 3 
 4 namespace Client
 5 {
 6     class Program
 7     {
 8         static void Main(string[] args)
 9         {
10             using (CalcServiceClient service = new CalcServiceClient())
11             {
12                 Console.WriteLine("Please input name:");
13                 String name = Console.ReadLine();
14                 Console.WriteLine(service.WelCome(name));
15                 Console.Read();
16             }
17         }
18     }
19 }
Client.Program
原文地址:https://www.cnblogs.com/hualongbei/p/4148985.html