C#webservice将json数据摘要到类中

时间:2016-10-12 19:15:40

标签: c# json web-services

我在弄清楚如何设置我的Web服务来消化json数据变量时遇到了麻烦。 我想在POST请求中发送数据并将其分配给类。

我的函数(见下文)该类始终为null OrderReprint 所以我错过了一大步。任何帮助都会很棒。

 public Boolean Test(OrderReprint oreprints)
    {

        Debug.WriteLine(OrderReprints.seq1);
        Debug.WriteLine(OrderReprints.client);
        Debug.WriteLine(OrderReprints.Filename);
        Debug.WriteLine(OrderReprints.formcode);
        Debug.WriteLine(OrderReprints.jobnum);
        Debug.WriteLine(OrderReprints.userid);
        Debug.WriteLine(OrderReprints.seq1);
        return true;
    }

我的界面看起来像这样

[OperationContract]
        [WebInvoke(Method = "POST",
             RequestFormat = WebMessageFormat.Json,
             BodyStyle = WebMessageBodyStyle.WrappedRequest,
             ResponseFormat = WebMessageFormat.Json,
             UriTemplate = "Test")]
        Boolean Test(OrderReprint oreprints);

我的数据合约类看起来像这样

 [DataContract]
public class OrderReprint
{
  [DataMember]
  public string Filename;
  [DataMember] 
  public string seq1;
  [DataMember]
  public string jobnum;
  [DataMember]
  public string formcode;
  [DataMember]
  public string userid;
  [DataMember]
  public string client;
}   

我的调用Ajax调用如下所示:

$.ajax({

    beforeSend: function (xhrObj) {
        xhrObj.setRequestHeader("Content-Type", "application/json");
        xhrObj.setRequestHeader("Accept", "application/json");
    },
    type: "POST",
    url: URL,
    dataType: "text",
    data: JSON.stringify(params),
}).then(function (data) {

    if (data.results) {
    /* (done something here*/
    }

}).fail(function (e) {

    errorAlert('Process Job', 'Error retriving job informaiton!');
});

2 个答案:

答案 0 :(得分:0)

我从OperationContract中删除了 BodyStyle ,它确实有效!

$1

BodyStyle = WebMessageBodyStyle.WrappedRequest

感谢大家的帮助..

答案 1 :(得分:-1)

我认为你的params没有转换为JSON。

在发送之前分配给变量并检查它是否有值。

  

var temp = JSON.stringify(params)