你的位置:首页 > ASP.net教程

[ASP.net教程]一个用Json格式来发送一个Post请求到WCF服务


测试实体类:(需要在客户端和服务端建了有相同字段名称的实体)

public class CompositeType  {    public CompositeType()    {      SubCompositeTypes = new List<SubCompositeType>() { new SubCompositeType() };    }    public bool BoolValue { get; set; }    public string StringValue { get; set; }    public List<SubCompositeType> SubCompositeTypes    {      get;      set;    }  }  public class SubCompositeType  {    bool boolValue = true;    string stringValue = "Hello ";    public bool BoolValue    {      get { return boolValue; }      set { boolValue = value; }    }    public string StringValue    {      get { return stringValue; }      set { stringValue = value; }    }  }


客户端请求代码:

#region JosnPost      CompositeType compositeType = new CompositeType      {        StringValue = "1",        BoolValue = false      };      DataContractJsonSerializer dcSerializer = new DataContractJsonSerializer(typeof(CompositeType));      MemoryStream stream = new MemoryStream();      dcSerializer.WriteObject(stream, compositeType);      string data = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);      //HttpClient client = new HttpClient();      //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));      string link = "http://localhost:1766/Service1.svc/CreateUser";      //HttpResponseMessage respondse = await client.PostAsync(link, new StringContent(data));      //string dataWithJason = await respondse.Content.ReadAsStringAsync();      var request = (HttpWebRequest)WebRequest.Create(new Uri(link));      request.ContentType = "application/json";      request.Method = "POST";      using (var requestStream = await request.GetRequestStreamAsync())      {        var writer = new StreamWriter(requestStream);        writer.Write(data);        writer.Flush();      }      using (var resp = await request.GetResponseAsync())      {        using (var responseStream = resp.GetResponseStream())        {          var reader = new StreamReader(responseStream);          var result = reader.ReadToEnd();        }      }

服务端接口定义:

[OperationContract]    [WebInvoke(      UriTemplate = "CreateUser",      RequestFormat = WebMessageFormat.Json,      ResponseFormat = WebMessageFormat.Json,      Method = "POST")]    string CreateUser(CompositeType compositeType);

服务端接口实现:

public string CreateUser(CompositeType compositeType)    {      return "OK" + compositeType.StringValue + " " + compositeType.BoolValue + " " + compositeType.SubCompositeTypes.FirstOrDefault().StringValue;    }

由于服务端需要实现REST服务,需要在web.config里重新配置下(cover serviceModel就可以了):

<system.serviceModel>  <services>   <service behaviorConfiguration="MyServiceBehavior" name="Server.Service1">    <endpoint address="" binding="webHttpBinding" behaviorConfiguration="web" contract="Server.IService1">     <identity>      <dns value="localhost"/>     </identity>    </endpoint>    <endpoint address="max" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>   </service>  </services>  <behaviors>   <endpointBehaviors>    <behavior name ="web">     <webHttp />    </behavior>   </endpointBehaviors>   <serviceBehaviors>    <behavior name="MyServiceBehavior">     <!-- To avoid disclosing metadata information, set the values below to false before deployment -->     <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>     <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->     <serviceDebug includeExceptionDetailInFaults="false"/>    </behavior>   </serviceBehaviors>  </behaviors>  <protocolMapping>   <add binding="basicHttpsBinding" scheme="https" />  </protocolMapping>  <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> </system.serviceModel>

经测试,在windows runtime项目中也可以用。