WCF是一種基于SOAP的通信協(xié)議,在.NET Framework中可用于構(gòu)建面向服務(wù)的應(yīng)用程序。在WCF中,可以使用DataContractSerializer來序列化和反序列化消息。然而,DataContractSerializer對(duì)于JSON格式的數(shù)據(jù)并不友好,因此需要使用JsonSerializer來處理。
接收J(rèn)SON消息時(shí),我們需要定義一個(gè)DataContract類來表示JSON數(shù)據(jù)的格式。例如,如果我們要接收以下JSON數(shù)據(jù):
{ "id": 1, "name": "John Doe", "age": 30 }
我們可以定義一個(gè)DataContract類如下:
[DataContract] public class Person { [DataMember(Name = "id")] public int Id { get; set; } [DataMember(Name = "name")] public string Name { get; set; } [DataMember(Name = "age")] public int Age { get; set; } }
在WCF服務(wù)中,我們可以定義一個(gè)接收Person對(duì)象的方法,并使用JsonDeserializer來反序列化JSON數(shù)據(jù):
[ServiceContract] public interface IPersonService { [OperationContract] void AddPerson(Person person); } public class PersonService : IPersonService { public void AddPerson(Person person) { // 處理Person對(duì)象 } } // 在配置文件中配置JsonDeserializer <system.serviceModel> <extensions> <behaviorExtensions> <add name="jsonDeserializer" type="System.ServiceModel.Configuration.JsonDeserializerElement, System.ServiceModel.Json"></add> </behaviorExtensions> </extensions> <behaviors> <serviceBehaviors> <behavior> <serviceMetadata httpGetEnabled="false" /> <serviceDebug includeExceptionDetailInFaults="true" /> <jsonDeserializer /> // 配置JsonDeserializer </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
在客戶端調(diào)用時(shí),我們可以使用HttpClient或者WebRequest來發(fā)送JSON數(shù)據(jù):
var person = new Person { Id = 1, Name = "John Doe", Age = 30 }; var json = JsonConvert.SerializeObject(person); // 將Person對(duì)象序列化為JSON字符串 var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost/PersonService.svc/AddPerson"); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { streamWriter.Write(json); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); }
通過以上方式,我們就可以在WCF服務(wù)中接收并處理JSON數(shù)據(jù)。