一、说明
1、创建控制台项目;
2、在项目中添加一个活多个WCF服务,并实现服务;
3、在需要启动WebService服务的地方启动该服务即可;
二、代码如下:
1、新建一个WCF服务——定义服务接口
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
2、新建一个WCF服务——实现服务
public class CalculatorService : ICalculator
{
public double Add(double n1, double n2)
{
return n1 + n2;
}
public double Subtract(double n1, double n2)
{
return n1 - n2;
}
public double Multiply(double n1, double n2)
{
return n1 * n2;
}
public double Divide(double n1, double n2)
{
return n1 / n2;
}
}
3、添加完WcF服务后会在应用程序配置文件中有入下节点
<services>
<service name="TestServer.CalculatorService">
<endpoint address="" binding="basicHttpBinding" contract="TestServer.ICalculator">
<!--TestServer.ICalculator服务定义的接口,根据自己定义进行修改-->
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
<host>
<baseAddresses>
<add baseAddress="http://101.111.111.111:8733/test/test/Service1/" />
<!--这个是要发布的服务地址,可以进行修改-->
</baseAddresses>
</host>
</service>
</services>
4、在要启动服务的地方启动服务监听
static void Main(string[] args)
{
Console.WriteLine("服务正在启动");
ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService));
//打开服务创建监听,并开始监听消息
serviceHost.Open();
Console.WriteLine("服务启动完成");
}
5、下面可以在客户端通过上面的服务地址”http://101.111.111.111:8733/test/test/Service1/“对服务进行调用
到这步就实现在控制台中实现webService的发布。