數據合同定義 c#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace Contracts { [DataContract] public class Person { [DataMember] public string Name { get; set; } [DataMember] public int Mark { get; set; } } }服務合同定義
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; namespace Contracts { [ServiceContract(SessionMode=SessionMode.Required)] public interface IAwardService { [OperationContract(IsOneWay = true,IsInitiating=true)] void SetPassMark(int passMark); [OperationContract] Person[] GetAwardedPeople(Person[] peopleToTest); } }新建WCF服務程序
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using Contracts; namespace wcfservice { // 注意: 使用「重構」菜單上的「重命名」命令,能夠同時更改代碼、svc 和配置文件中的類名「AwardService」。 public class AwardService : IAwardService { private int passMark; public void SetPassMark(int passMark) { this.passMark = passMark; } public Person[] GetAwardedPeople(Person[] peopleToTest) { List<Person> result = new List<Person>(); foreach (Person person in peopleToTest) { result.Add(person); } return result.ToArray(); } } }修改Web.config中的服務配置
<system.serviceModel> <protocolMapping> <add scheme="http" binding="wsHttpBinding"/> </protocolMapping> </system.serviceModel>新建客戶端(控制檯應用程序)
namespace Client { class Program { static void Main(string[] args) { Person[] persons = new Person[] { new Person{Mark=46,Name="Jim"}, new Person{Mark=73,Name="Tom"}, new Person{Mark=92,Name="John"}, new Person{Mark=84,Name="Geogre"} }; Console.WriteLine("People"); OutputPeople(persons); IAwardService client = ChannelFactory<IAwardService>.CreateChannel( new WSHttpBinding(),new EndpointAddress("http://localhost:51425/AwardService.svc")); client.SetPassMark(70); Person[] awardedPeople = client.GetAwardedPeople(persons); Console.WriteLine(); Console.WriteLine("Award people:"); OutputPeople(awardedPeople); Console.ReadKey(); } static void OutputPeople(Person[] persons) { foreach (Person person in persons) { Console.WriteLine("{0},mark:{1}",person.Name,person.Mark); } } } }