WCF Demo
注意:
引用程序集System.ServiceModel.dll
帮助:项目的配置文件右键-编辑WCF配置,此工具可以方便的配置wcf配置
一.定义服务契约:(本质就是接口加ServiceContract特性)
[ServiceContract] public interface IBookService { [OperationContract] string GetBook(int num); }
二.实现契约:(实现接口)
public class BookService : IBookService { public string GetBook(int num) { return $"第{num}章内容"; } }
三.服务配置:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="UserBinding" />
<binding name="BookBinding" />
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="UserBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
</behavior>
<behavior name="BookBehavior">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="UserBehavior" name="LFN.TCAL.WCFService.UserService">
<endpoint address="UserService" binding="basicHttpBinding" bindingConfiguration="UserBinding"
name="UserEndpoint" contract="LFN.TCAL.WCFService.IUserService" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:55958/" />
</baseAddresses>
</host>
</service>
<service behaviorConfiguration="BookBehavior" name="LFN.TCAL.WCFService.BookService">
<endpoint address="BookService" binding="basicHttpBinding" bindingConfiguration="BookBinding"
name="BookEndpoint" contract="LFN.TCAL.WCFService.IBookService" />
<host>
<baseAddresses>
<add baseAddress="http://localhost:55958/" />
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
四.实现契约:
客户端项目新建BookServiceClient 类并继承ClientBase类,实现契约接口IBookService
public class BookServiceClient : ClientBase<IBookService>, IBookService { public string GetBook(int num) { return base.Channel.GetBook(num); } }
五.客户端配置:
<system.serviceModel>
<behaviors />
<bindings>
<basicHttpBinding>
<binding name="BookBinding" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8001/BookService.svc/BookService"
binding="basicHttpBinding" bindingConfiguration="BookBinding"
contract="LFN.TCAL.WCFService.IBookService" name="BookEndpoint"
kind="" endpointConfiguration="" />
</client>
</system.serviceModel>
六.客户端调用WCF服务:
class Program { static void Main(string[] args) { using (BookServiceClient client = new BookServiceClient()) { var str = client.GetBook(3); Console.WriteLine(str); Console.Read(); } } }
结果输出:第3章内容