0

我正在尝试使用 WCF 从另一个应用程序中获取对象。使用内置类它可以正常工作,但是在尝试从 WCF 操作返回自定义接口类型时遇到了问题。

无论我在两个应用程序中分别包含接口,还是将其指定为共享程序集,我都会得到相同的结果:带有消息“从管道读取错误:无法识别的错误 109”的 CommunicationException。

界面如下所示:

[ServiceContract]
public interface IBase {
    int IntTest {
        [OperationContract]
        get;
    }
    String StringTest {
        [OperationContract]
        get;
    }
    IOther OtherTest {
        [OperationContract]
        get;
    }
}

[ServiceContract]
public interface IOther {
    String StringTest {
        [OperationContract]
        get;
    }
}

我的服务器如下所示:

public partial class MainWindow : Window {
    private Base fb;
    private ServiceHost host;

    public MainWindow() {
        InitializeComponent();
        fb = new Base();
        host = new ServiceHost(fb, new Uri[] { new Uri("net.pipe://localhost") });
        host.AddServiceEndpoint(typeof(IBase), new NetNamedPipeBinding(),
            "PipeReverse");
        host.Open();
    }

    private void Window_Closing(object sender, CancelEventArgs e) {
        host.Close();
    }
}

这是我的接口实现:

[Serializable]
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class Base : MarshalByRefObject, IBase {
    public int IntTest {
        get { return 4; }
    }

    public string StringTest {
        get { return "A string from Base"; }
    }

    public IOther OtherTest {
        get { return new Other(); }
    }
}

[Serializable]
[DataContract]
public class Other : MarshalByRefObject, IOther {
    [DataMember]
    public string StringTest {
        get { return "A string from Other"; }
    }

}

客户端看起来像这样:

public partial class Form1 : Form {

    IBase obj;

    public Form1() {
        InitializeComponent();
        ChannelFactory<IBase> pipeFactory = new ChannelFactory<IBase>(
            new NetNamedPipeBinding(), new EndpointAddress(
            "net.pipe://localhost/PipeReverse"));

        obj = pipeFactory.CreateChannel();
    }


    private void button2_Click(object sender, EventArgs e) {

        Console.WriteLine("Returns: " + obj.StringTest + " " + 
            obj.StringTest.Length);
        Console.WriteLine("Returns: " + obj.IntTest);
        Console.WriteLine(obj.OtherTest);

    }
}

除了这一行之外,一切都像魅力一样:

Console.WriteLine(obj.OtherTest);

它给了我一个 CommunicationException 消息“从管道读取错误:无法识别的错误 109”。据我所知,这是由于故障状态导致的管道损坏,但我不知道为什么,或者更重要的是如何修复它。有任何想法吗?

我没有配置文件,因为上面的代码中已经完成了所有操作,所以我不知道如何打开跟踪,否则我也会包含它。

4

2 回答 2

2

返回的属性OtherTest需要是具体类型而不是接口,否则序列化将不起作用。

于 2009-04-18T15:43:34.803 回答
0

这通常是一个序列化错误。查看 [KnownType] 属性。测试这一点的最简单方法是直接调用 DataContractSerializer。您可以使用它的 WriteObject 和 ReadObject 方法来获取真正的序列化错误。您还可以检查流(通常是 FileStream)以确保您正确键入序列化。

于 2009-04-18T12:24:44.670 回答