将Android类发送到WCF Web服务

时间:2013-07-31 08:36:40

标签: c# android .net wcf rest

我正在尝试使用REST来发送到公开的Web服务。但我得到的是400(不良请求。)

你如何在REST中发送模型,这将正确映射到另一侧的模型。我不想做的是,在连接点中单独暴露所有100个参数。

    [OperationContract]
    [WebInvoke(
        Method = "POST",
        UriTemplate = "SaveData",
        BodyStyle = WebMessageBodyStyle.WrappedRequest,
        ResponseFormat = WebMessageFormat.Json,
        RequestFormat = WebMessageFormat.Json)]
    void SaveData(datum data);

但我无法做的是传递有效的基准对象。

     // Build JSON string
     JSONStringer vehicle;
    try {
        vehicle = new JSONStringer()
             .object()
                 .key("datum")
                     .object()
                         .key("ID").value(5)
                         .key("Name").value("test")
                         .key("No").value(54)
                         .key("Description").value("Test")
                     .endObject()
                 .endObject(); 

      HttpPost request = new HttpPost(address + "/SaveData");
     Log.d("WebInvoke", "Connection : " + address + "/SaveData");
     request.setHeader("Accept", "application/json");
     request.setHeader("Content-type", "application/json");
         StringEntity entity = new StringEntity(vehicle.toString());
         Log.d("StringEntity", vehicle.toString());
         request.setEntity(entity);

         // Send request to WCF service
         DefaultHttpClient httpClient = new DefaultHttpClient();
         HttpResponse response = httpClient.execute(request);

         Log.d("WebInvoke", "Saving : " +    response.getStatusLine().getStatusCode());
             // Saving : 400

基准课程:

[DataContract]
public partial class datum
{
    [DataMember(Name = "ID")]
    public int ID { get; set; }
       [DataMember(Name = "Name")]
    public string Name { get; set; }
     [DataMember(Name = "No")]
    public Nullable<int> No { get; set; }

        [DataMember(Name = "Description")]
    public string Description { get; set; }
}

1 个答案:

答案 0 :(得分:1)

应该是:

vehicle = new JSONStringer()
             .object()
                 .key("data")
                     .object()
                         .key("ID").value(5)
                         .key("Name").value("test")
                         .key("No").value(54)
                         .key("Description").value("Test")
                     .endObject()
                 .endObject(); 

来源: WCF BodyStyle WrappedRequest doesn't work for incoming JSON param?