如果要运行基本的WCF服务,需要基本的几个步骤:
(1)为服务创建基地址
为服务基址创建Uri实例。包括Http方案,计算机,端口,服务路径
例如:Uri _baseAddress = new Uri("http://localhost:8990/FirstService/Service");
(2)服务创建宿主环境以承载服务
1 创建ServiceHost实例,指定服务契约和基址。
例如:
ServiceHost host = new ServiceHost(typeof(CaculateService), _baseAddress);
2 为服务添加终结点
添加终结点以公开服务。终结点ServiceEndpoint由ABC组成:
·Address,告知客户端服务所在位置。地址由EndpointAddress表示。
·Binding,指定如何与终结点通信,指定传输协议、编码(二进制,文本,MTOM)、安全
·Contract,概述了终结点向客户端公开的功能。三种基本的契约类型与基本的消息交换模式相对应:单向,RR,双向
例如:
EndpointAddress _Address = new EndpointAddress(_baseAddress);
WSHttpBinding _Binding = new WSHttpBinding();
ContractDescription _Contract =
ContractDescription.GetContract(typeof(ICaculate));
ServiceEndpoint endpoint = new ServiceEndpoint(_Contract, _Binding, _Address);
3 启用元数据交换
例如:
ServiceMetadataBehavior meta = new ServiceMetadataBehavior();
meta.HttpGetEnabled = true;
host.Description.Behaviors.Add(meta);
4 打开宿主
完整代码:
(1)契约
[ServiceContract(Namespace = "http://w3333.com")]
public interface ICaculate
{
[OperationContract]
double Plus(double a, double b);
[OperationContract]
double Subtract(double a, double b);
[OperationContract]
double Multiply(double a, double b);
[OperationContract]
double Divide(double a, double b);
}
public class CaculateService : ICaculate
{
public double Plus(double a, double b)
{
Console.WriteLine(a+"+"+b+"="+(a+b));
return a + b;
}
public double Subtract(double a, double b)
{
Console.WriteLine(a + "-" + b + "=" +( a - b));
return a - b;
}
public double Multiply(double a, double b)
{
Console.WriteLine(a + "*" + b + "=" + a * b);
return a * b;
}
public double Divide(double a, double b)
{
Console.WriteLine(a + "/" + b + "=" + a / b);
return a / b;
}
}
(2)控制台宿主
static void Main(string[] args)
{
//创建地址
Uri _baseAddress = new Uri("http://localhost:8990/FirstService/Service");
EndpointAddress _Address = new EndpointAddress(_baseAddress);
WSHttpBinding _Binding = new WSHttpBinding();
ContractDescription _Contract = ContractDescription.GetContract(typeof(ICaculate));
ServiceEndpoint endpoint = new ServiceEndpoint(_Contract, _Binding, _Address);
//创建宿主
ServiceHost host = new ServiceHost(typeof(CaculateService), _baseAddress);
//添加终结点ABC
host.Description.Endpoints.Add(endpoint);
//启用元数据交换
ServiceMetadataBehavior meta = new ServiceMetadataBehavior();
meta.HttpGetEnabled = true;
host.Description.Behaviors.Add(meta);
host.Open();
Console.WriteLine("service Begin——");
Console.ReadLine();
host.Close();
}