【问题标题】:Passing complex type to windows service with WCF使用 WCF 将复杂类型传递给 Windows 服务
【发布时间】:2014-04-24 02:54:08
【问题描述】:

我有一个 Windows 服务和 winform 前端应用程序。我需要能够调用并将数据往​​返传递给服务中的方法。我通过定义一个接口实现了这一点,并且可以毫无问题地传递字符串。

[ServiceContract]
public interface IStringReverser
{
    [DataContractFormat]
    [OperationContract]
    string ReverseString(string value);
}

我现在正试图返回一个复杂的数据类型,并已更改代码:

[ServiceContract]
public interface IStringReverser
{
    [DataContractFormat]
    [OperationContract]
    DTO ReverseString(string value);
}

[Serializable]
public class DTO
{
    public int Id { get; set; }
    public string Name { get; set; }
}

我的实现是这样的:

public class StringReverser : IStringReverser
{
    public DTO ReverseString(string value)
    {
        char[] retVal = value.ToCharArray();
        int idx = 0;
        for (int i = value.Length - 1; i >= 0; i--)
            retVal[idx++] = value[i];

        var dto = new DTO();
        dto.Name = retVal.ToString();
        dto.Id = 122;
        return dto;
    }
}

我并不特别关注数据是如何传输的。我收到一个错误:

格式化程序在尝试反序列化消息时抛出异常:尝试反序列化参数http://tempuri.org/:ReverseStringResult 时出错。不应出现来自命名空间“http://tempuri.org/”的 InnerException 消息是“EndElement”“ReverseStringResult”。期待元素'_x003C_Id_x003E_k__BackingField'。'。有关详细信息,请参阅 InnerException。

在 winform 中,我正在创建与此的连接:

private IStringReverser pipeProxy;
    public Form1()
    {
        InitializeComponent();

        ChannelFactory<IStringReverser> httpFactory =
            new ChannelFactory<IStringReverser>(
              new BasicHttpBinding(),
              new EndpointAddress(
                "http://localhost:8000/Reverse"));

        ChannelFactory<IStringReverser> pipeFactory =
            new ChannelFactory<IStringReverser>(
              new NetNamedPipeBinding(),
              new EndpointAddress(
                "net.pipe://localhost/PipeReverse"));

        //IStringReverser httpProxy = httpFactory.CreateChannel();
        pipeProxy = pipeFactory.CreateChannel();
    }

我不明白错误消息或如何更正它。我如何定义它是如何反序列化的?序列化可以吗?

【问题讨论】:

    标签: c# wcf


    【解决方案1】:

    使用数据合同:

    [DataContract]
    public class DTO
    {
        [DataMember]
        public int Id { get; set; }
        [DataMember]
        public string Name { get; set; }
    }
    

    【讨论】:

    • 这解决了错误,但我得到的数据是空的,这意味着 Id 是 0 并且 Name 是 null
    • 我什至将 DTO 对象移动到 StringReverser 类的字段中,认为它可能超出了范围,但没有解决。
    • 我建议你一路跌倒。用类似于DTO dto = new DTO{Id=1,Name="John"};return dto; 的虚拟代码替换从数据库(或任何地方)填充 DTO 的代码您也可以尝试调试。
    • 这显然是问题的一部分——我不知道如何调试它,因为它在 Windows 服务中并且必须安装和启动。我还按照建议初始化了对象并得到相同的空结果。
    • 如果您返回常量数据,但没有收到任何数据,那么您没有收到您返回的数据,并且应该想知道您是否正在调用该服务。您是否在每次构建后重新启动 Windows 服务?你可以使用Debug->Attach to Process来调试windows服务。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 2011-01-04
    • 1970-01-01
    • 2015-11-15
    • 2014-01-06
    • 2015-12-20
    相关资源
    最近更新 更多