【问题标题】:Why does my WebGet return an empty class为什么我的 WebGet 返回一个空类
【发布时间】:2015-06-09 12:30:25
【问题描述】:

当我尝试检索一个充满数据的类时,我从未检索到正确的数据。下面类中的布尔值总是返回 false。

当我从 Postman 或 Chrome 调用相同的 GetState 函数而不进行任何更改时,我确实得到了我期望的结果

我有一个类似这样的类:

        [DataContract]
        public class State
        {
            [DataMember]
            public bool Camera_1_Ok { get; set; }
            [DataMember]
            public bool Camera_2_Ok { get; set; }
            [DataMember]
            public bool Camera_3_Ok { get; set; }
        }

我的 ServiceContract 界面如下所示:

        [ServiceContract]
        interface IConnectionService
        {
            [OperationContract]
            [WebGet(BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetState", RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
            State GetState();
        }

GetState 实现如下所示:

        [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
        public sealed class WCFServer : IConnectionService
        {
            public State GetState()
            {
                State tempState = new State();
                State.Camera_1_OK = true;
                State.Camera_2_OK = true;
                State.Camera_3_OK = true;

                return tempState;
            }

我确保服务的两端具有相同的“State”类和相同的“IConnectionService”接口。

为什么返回给调用机器的类中的布尔值永远不会设置?当我从 Chrome 或 Postman 调用该函数时,我怎么能得到正确的数据?

类似问题的 Awnsers 提到了 [DataContract][DataMember] 属性,但我已经将这些添加到我的课程中。

PS:当我在服务的两侧将ResponseFormat 设置为WebMessageFormat.Json 时,我得到了预期的数据。遗憾的是,由于请求了Xml 格式,因此这不是解决方案。

【问题讨论】:

  • 使用 Fiddler 检查请求,并了解在两种情况下发出请求时它们有何不同。也尽量不要设置响应格式,让框架处理它。它从“Accept”响应头中决定响应格式,并以适当的格式返回。
  • 我找不到与提琴手的任何区别,除非它是 Json 或 XML 格式的 Content-Type 。所以那里没有运气。
  • 你能发布一下你的配置的样子吗?

标签: c# json xml wcf rest


【解决方案1】:
BodyStyle = WebMessageBodyStyle.Bare

然后从您的函数中返回一个 System.IO.Stream。

之后,尝试在接收器处反序列化您的流。

【讨论】:

    猜你喜欢
    • 2017-07-25
    • 2022-01-09
    • 2017-09-04
    • 2015-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多