不说废话,直接上代码。以下服务创建是在独立的WCF类库中,若采用WCF应程程序,定义及创建服务代码均相同,但文件名不同,是CalculatorService.svc
第一步,定义服务契约(Service Contract),即:定义一个服务接口
using System.ServiceModel; namespace WcfServiceLibrary1
{
[ServiceContract(Namespace="http://www.zuowenjun.cn")]
public interface ICalculator
{
[OperationContract]
double Add(double x, double y); [OperationContract]
double Subtract(double x, double y); [OperationContract]
double Multiply(double x, double y); [OperationContract]
double Divide(double x, double y);
}
}
第二步,实现服务契约,即:实现第一步的接口
namespace WcfServiceLibrary1
{
public class CalculatorService : ICalculator
{
public double Add(double x, double y)
{
return x + y;
} public double Subtract(double x, double y)
{
return x - y;
} public double Multiply(double x, double y)
{
return x * y;
} public double Divide(double x, double y)
{
return x / y;
}
}
}
第三步,创建服务寄宿程序
WCF服务需要依存一个运行着的进程(宿主),服务寄宿就是为服务指定一个宿主的过程。WCF是一个基于消息的通信框架,采用基于终结点(Endpoint)的通信手段。终结点由地址(Address)、绑定(Binding)和契约(Contract)三要素组成
服务寄宿程序可以是控制台应用程序,winform,Windows服务,以及IIS(IIS的寄宿方法与以下代码实现不同)
1.通过代码来实现服务寄宿
using System;
using WcfServiceLibrary1;
using System.ServiceModel;
using System.ServiceModel.Description; namespace ConsoleApplicationHost
{
class Program
{
static void Main(string[] args)
{
BuildServiceHostByCode();
} static void BuildServiceHostByCode()
{
using (ServiceHost host = new ServiceHost(typeof(CalculatorService)))
{
host.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "http://127.0.0.1:12300/CalculatorService");
if (host.Description.Behaviors.Find<ServiceMetadataBehavior>() == null)
{
ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
behavior.HttpGetEnabled = true;
behavior.HttpGetUrl = new Uri("http://127.0.0.1:12300/CalculatorService/metadata");
host.Description.Behaviors.Add(behavior);
}
host.Opened += (s, e) => { Console.WriteLine("CalculaorService已经启动,按按回车键终止服务!"); };
host.Open();
Console.ReadLine();
}
}
}
}
2.通过Config配置文件来实现服务寄宿(可以直接使用VS提供的配置工具来配置WCF,方法:工具(Tools)菜单-->选择“WCF服务配置编辑器”子项)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServicemetadatabehavior">
<serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:12306/CalculatorService/metadata"/>
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WcfServiceLibrary1.CalculatorService" behaviorConfiguration="CalculatorServicemetadatabehavior">
<endpoint address="http://127.0.0.1:12306/CalculatorService" binding="wsHttpBinding" contract="WcfServiceLibrary1.ICalculator">
</endpoint>
</service>
</services>
</system.serviceModel>
</configuration>
using System;
using WcfServiceLibrary1;
using System.ServiceModel;
using System.ServiceModel.Description; namespace ConsoleApplicationHost
{
class Program
{
static void Main(string[] args)
{
BuildServiceHostByConfig();
} static void BuildServiceHostByConfig()
{
using (ServiceHost host = new ServiceHost(typeof(CalculatorService)))
{
host.Opened += (s, e) => { Console.WriteLine("CalculaorService已经启动,按按回车键终止服务!"); };
host.Open();
Console.ReadLine();
}
}
}
}
3.通过IIS来实现服务寄宿
创建一个Asp.net空Web应用程序,然后添加一个WCF服务文件。这里WCF服务文件与Web 服务中的.asmx文件类似。基于IIS的服务寄宿要求相应的WCF服务具有相应的.svc文件,.svc文件部署于IIS站点中,对WCF服务的调用体现在对.svc文件的访问上。
WCF服务文件的内容很简单,仅仅包含一个ServiceHost指令,该指令具有一个必须的Service属性和一些可选的属性。所以对应的.svc文件内容如下所示:
<%@ ServiceHost Language="C#" Debug="true" Service="WcfServiceLibrary1.CalculatorService" %>
Web.Config配置如下(WCF服务配置均相同,唯一不同的是在添加终结点中无需指定地址,因为.svc所在的地址就是服务的地址。):
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServicemetadatabehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="WcfServiceLibrary1.CalculatorService" behaviorConfiguration="CalculatorServicemetadatabehavior">
<endpoint binding="wsHttpBinding" contract="WcfServiceLibrary1.ICalculator">
</endpoint>
</service>
</services>
</system.serviceModel>
</configuration>
第四步,在客户端程序中使用(调用)WCF服务
1.根据WCF服务发布的元数据地址引用WCF服务,系统自动生成一系列的类,包含一个服务契约接口、一个服务代理对象和其他相关的类。
2.直接使用系统自动生成的客户服务代理类CalculatorClient来调用相关方法。
using System;
using ConsoleApplicationClient.CalculatorServices;
using System.ServiceModel; namespace ConsoleApplicationClient
{
class Program
{
static void Main(string[] args)
{
CallServiceByReference();
Console.WriteLine("按任意键结束。");
Console.Read();
} static void CallServiceByReference()
{
using (CalculatorClient proxy = new CalculatorClient())
{
CallService(proxy.Add);
CallService(proxy.Subtract);
CallService(proxy.Multiply);
CallService(proxy.Divide);
}
} static void CallService(Func<double, double, double> serviceMethod)
{
Console.Write("请输入第1数字:");
double input1 = double.Parse(Console.ReadLine());
Console.Write("请输入第2数字:");
double input2 = double.Parse(Console.ReadLine());
double result = serviceMethod(input1, input2);
string methodName = serviceMethod.Method.Name;
Console.Write("两数字{0}结果:{1}\n", methodName, result);
}
}
}
3.上述使用方法的前提是引用WCF服务元数据地址,然后由VS系统自动生成一系列的类,我们也可在不引用的情况下,使用WCF服务,前提是必需创建或引用文中第一步的服务契约及服务实现,然后便可使用如下方法:
using System;
using ConsoleApplicationClient.CalculatorServices;
using System.ServiceModel; namespace ConsoleApplicationClient
{
class Program
{
static void Main(string[] args)
{
CallServiceByCode();
Console.WriteLine("按任意键结束。");
Console.Read();
} static void CallServiceByCode()
{ //using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>(new WSHttpBinding(), "http://127.0.0.1:12306/CalculatorService"))
//如果CONFIG文件中有配置endpoint,则可使用下面的构造函数(参数为指定endpoint的配置名称),若没有配置则需使用上面的构造函数(参数为指定绑定方式及服务地址)
using (ChannelFactory<ICalculator> channelFactory = new ChannelFactory<ICalculator>("WSHttpBinding_ICalculator"))
{
ICalculator proxy = channelFactory.CreateChannel();
using (proxy as IDisposable)
{
CallService(proxy.Add);
CallService(proxy.Subtract);
CallService(proxy.Multiply);
CallService(proxy.Divide);
}
}
} static void CallService(Func<double, double, double> serviceMethod)
{
Console.Write("请输入第1数字:");
double input1 = double.Parse(Console.ReadLine());
Console.Write("请输入第2数字:");
double input2 = double.Parse(Console.ReadLine());
double result = serviceMethod(input1, input2);
string methodName = serviceMethod.Method.Name;
Console.Write("两数字{0}结果:{1}\n", methodName, result);
}
}
}
客户端配置文件如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<client>
<endpoint address="http://127.0.0.1:12306/CalculatorService"
binding="wsHttpBinding"
contract="CalculatorServices.ICalculator" name="WSHttpBinding_ICalculator">
</endpoint>
</client>
</system.serviceModel>
</configuration>
说明:发表这篇文章参考了如下作者的文章:
文章同步发表于我的个人网站:http://www.zuowenjun.cn/post/2015/03/24/132.html