1.契约接口(ITest)
namespace WcfService.Server { [ServiceContract] public interface ITest { [OperationContract] string GetHello(); } }
接口需要使用ServiceContract标记接口,用OperationContract标记方法;
2.继承ITest接口契约并实现接口
namespace WcfService.Server { public class Test : ITest { public string GetHello() { return "Hello"; } } }
实现契约接口即可;
3.编写服务的配置信息
<?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service name="WcfService.Server.Test"> <endpoint address="http" binding="basicHttpBinding" contract="WcfService.Server.ITest" /> <endpoint address="nettcp" binding="netTcpBinding" contract="WcfService.Server.ITest" /> <host> <baseAddresses> <add baseAddress="http://localhost:8080/wcf" /> <add baseAddress="net.tcp://localhost:8081/wcf" /> </baseAddresses> </host> </service> </services> </system.serviceModel> </configuration>
service中的name为完整对象的名称;
endpoint中的address为相对路径,binding为传递协议,使用basicHttpBinding实际使用soap,和webservice类似,contract为契约接口完整名称;
hostz中的baseAddresses添加对应协议的绝对地址和端口号;
最终客户端访问地址为:host中的baseAddress+endpoint的address;
4.启动服务
namespace WcfService.Server { class Program { static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(Test))) { host.Open(); Console.WriteLine("Ready..."); Console.ReadLine(); host.Close(); } } } }
使用ServiceHost启动服务
项目需要引用System.ServiceModel