假设所有工程的命名空间是demo。
[ServiceContract] Interface IMath { [Operationcontract] Int add (int a, int b); }
添加一个新类,如Math实现该接口。
Public class Math : IMath{ Int add(int a,int b){ Return (a+b); } }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
namespace HelloServiceHost
{
class Program
{
static void Main(string[] args)
{
using (MyHelloHost host = new MyHelloHost())
{
host.openService();
}
}
}
public class MyHelloHost : IDisposable
{
private ServiceHost serviceHost = null;
/// <summary>
/// base address
/// </summary>
//public const string baseAddress = "net.pipe://localhost";
public const string baseAddress = "http://localhost";
/// <summary>
/// 服务名称
/// </summary>
public const string serviceAddress = "MathService";
/// <summary>
/// 实现服务的契约
/// </summary>
public static readonly Type serviceType=typeof(demo.Math);
/// <summary>
/// 接口契约
/// </summary>
public static readonly Type contractType = typeof(HelloService.IHelloService);
/// <summary>
/// 定义一个服务绑定
/// </summary>
//public static readonly Binding helloBinding = new NetNamedPipeBinding();
public static readonly Binding helloBinding = new BasicHttpBinding();
/// <summary>
/// 构造服务宿主
/// </summary>
private void createHelloServiceHost()
{
///创建服务对象
serviceHost = new ServiceHost(serviceType,new Uri[]{new Uri(baseAddress)});
///添加一个终结点
serviceHost.AddServiceEndpoint(contractType, helloBinding, serviceAddress);
}
public ServiceHost ServiceHost
{
get { return serviceHost; }
}
/// <summary>
/// 打开服务
/// </summary>
public void openService()
{
Console.WriteLine("Service is starting...");
serviceHost.Open();
Console.WriteLine("Service running...");
}
public MyHelloHost()
{
createHelloServiceHost();
}
public void Dispose()
{
if (null != serviceHost)
{
(serviceHost as IDisposable).Dispose();
}
}
}
}
1a) 修改App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<service name="demo.Math" behaviorConfiguration="TestBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8001/MathService"/>
</baseAddresses>
</host>
<endpoint address="" binding="basicHttpBinding" contract="demo.IHello" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="TestBehavior">
<serviceMetadata httpGetEnabled="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
1b) 修改代码如下
class Program
{
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(demo.Math));
host.Open();
Console.ReadKey();
}
}
WCF学习笔记 -- 如何用C#开发一个WebService,布布扣,bubuko.com
WCF学习笔记 -- 如何用C#开发一个WebService
原文:http://www.cnblogs.com/C-Sharp2/p/3872653.html