数据合同定义
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);
}
}
}
}