using System.IO; using System.Runtime.Serialization; using System.ServiceModel; using System.Xml.Serialization; namespace WcfService { [ServiceContract] public interface IBookService { [OperationContract] string GetBook(int id); } public class BookService : IBookService { public string GetBook(int id) { var book = new Book() { Id = id, Name = "DB 2" }; using (var stringWriter = new StringWriter()) { var xmlSerializer = new XmlSerializer(book.GetType()); xmlSerializer.Serialize(stringWriter, book); return stringWriter.ToString(); } } } [DataContract] public class Book { [DataMember] public int Id { get; set; } [DataMember] public string Name { get; set; } } }
using System; using System.ServiceModel; using WcfService; namespace WcfHost { class Program { static void Main(string[] args) { try { using (ServiceHost host = new ServiceHost(typeof(BookService))) { host.Opened += delegate { Console.WriteLine("BookService,使用配置文件,按任意键终止服务"); }; host.Open(); Console.ReadLine(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } } <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <behaviors> <serviceBehaviors> <behavior name="metadataBehavior"> <serviceMetadata httpGetEnabled="true" httpGetUrl="http://127.0.0.1:8080/BookService/metadata" /> </behavior> </serviceBehaviors> </behaviors> <services> <service behaviorConfiguration="metadataBehavior" name="WcfService.BookService"> <endpoint address="http://127.0.0.1:8080/BookService" binding="wsHttpBinding" bindingConfiguration="" contract="WcfService.IBookService" /> </service> </services> </system.serviceModel> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> </startup> </configuration>
using System; using System.Collections.Generic; using System.ServiceModel; using WcfService; namespace WcfClient { class Program { static void Main(string[] args) { using (ChannelFactory<IBookService> channelFactory = new ChannelFactory<IBookService>("WSHttpBinding_IBookService")) { var proxy = channelFactory.CreateChannel(); using (proxy as IDisposable) { Console.WriteLine(proxy.GetBook(4)); } } } } } <?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" /> </startup> <system.serviceModel> <bindings> <wsHttpBinding> <binding name="WSHttpBinding_IBookService" /> </wsHttpBinding> </bindings> <client> <endpoint address="http://127.0.0.1:8080/BookService" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IBookService" contract="WcfService.IBookService" name="WSHttpBinding_IBookService"> <identity> <userPrincipalName value="DEEP-1712200247\Administrator" /> </identity> </endpoint> </client> </system.serviceModel> </configuration>