【问题标题】:Changing JSON response root node message in WCF在 WCF 中更改 JSON 响应根节点消息
【发布时间】:2023-03-10 05:05:01
【问题描述】:

我在 WCF 中创建了一个 REST GetTime 服务,该服务返回 JSON 作为响应消息。 WebMessageBodyStyle 也被设置为 Wrapped,因此它会有一个与它返回的数据相关联的 ID。但是当我使用 Fiddler 测试我的服务时,响应字符串是:

{"GetTimeResult":"2010614104013"}

由于字符串 ID 上方的响应是 GetTimeResult,我想知道是否有任何方法可以将该位测试更改为时间戳。所以它看起来像这样:

{"timestamp":"2010614104013"}

干杯。

【问题讨论】:

    标签: wcf json web-services wcf-rest


    【解决方案1】:

    正如this 文章中所指出的,假设您没有在数据协定中明确使用数据成员,并且想要返回时间戳作为响应的简单字符串。只需将注解[return: MessageParameter(Name = "timestamp")] 与您的操作合同方法一起使用即可:

    [OperationContract]
    [WebInvoke(Method = "GET", UriTemplate = "/timestamps", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
    [return: MessageParameter(Name = "timestamp")]
    string GetStringTimestamp();
    

    【讨论】:

      【解决方案2】:

      如果您在代码中使用 DataContract/DataMember 属性,则添加一个名称(以及一些其他命名参数)。

      [DataMember(Name = "timestamp")]
      public string GetTimeResult
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多