【问题标题】:Post json string to WCF method将 json 字符串发布到 WCF 方法
【发布时间】:2016-04-14 10:28:58
【问题描述】:

我有 WCF 方法

[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
string PostNewOrder(string OrderData);

这是我发布的json字符串

{
    "customerId": " ",
    "langCode": "SE",
    "timeZone": "38",
    "orderNumber": "1122519",
    "orderDate": "2016-04-13 15:56:36",
    "deliveryNumber": "625615",
    "devices": "000000001050840;",
    "transactionId": "24",
    "shipDate": "2016-04-13 16:41:31"
}

但我在 WCF 方法中将 OrderData 设为 null

如果我发布字符串

"{\"customerId\":\" \",\"langCode\":\"SE\",\"timeZone\":\"38\",\"orderNumber\":\"1122519\",\"orderDate\":\"2016-04-13 15:56:36\",\"deliveryNumber\":\"625615\",\"devices\":\"000000001050840;\",\"transactionId\":\"24\",\"shipDate\":\"2016-04-13 16:41:31\"}"

它工作正常,但这不是一个正确的 json,在此先感谢..

【问题讨论】:

  • 您能告诉我们您将对象转换为 json 字符串的代码吗?
  • 不,我只是使用 post man 客户端将 json 字符串发布到 wcf 方法。

标签: c# json wcf


【解决方案1】:

您的合同应该类似于 -

    [OperationContract]
    [WebInvoke(Method = "POST",
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json ,
    UriTemplate="/post")]
    string PostNewOrder(RootObject OrderData);

RootObject 应该是这样的 -

public class RootObject
{
    public string customerId { get; set; }
    public string langCode { get; set; }
    public string timeZone { get; set; }
    public string orderNumber { get; set; }
    public string orderDate { get; set; }
    public string deliveryNumber { get; set; }
    public string devices { get; set; }
    public string transactionId { get; set; }
    public string shipDate { get; set; }
}

您发布的是 json 对象表示,而不是字符串,并且 WCF 运行时应将内容反序列化为它在服务器上的等效强类型对象。

【讨论】:

    【解决方案2】:

    我认为您需要从 OperationContract 中删除 RequestFormat 和 ResponseFormat

    【讨论】:

    • 是的,我试过了,但我收到了这个错误:服务器在处理请求时遇到错误。异常消息是“反序列化 System.String 类型的对象时出错。应来自命名空间“”的结束元素“根”。从命名空间 ''.' 中找到元素 'customerId'。
    • 像这样: var text = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName": "Anna" , "lastName":"Smith" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}';
    • 请求负载甚至不是字符串
    【解决方案3】:

    这是一个老问题,但如果有人需要这个答案:

    您需要将您的 json 字符串包装在另一个字符串中。

    我使用的是角度 - 所以在我的情况下我这样做了:

    let doc = new FileData();
    ...
    let jsonObj = JSON.stringify(doc); //json object string
    
    let strObj = JSON.stringify(jsonObj); //json object string wrapped with string
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 1970-01-01
      • 2015-09-08
      • 2012-12-21
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      相关资源
      最近更新 更多