簡體   English   中英

Wcf ChannelFactory

[英]Wcf ChannelFactory

我對WCF和Channel Factory的使用有疑問。

在主機上:

[ServiceContract]
public interface IGetMessage 
{
    [OperationContract]
    string ShowMessage(Sample p, string Username, string Password);
}

[DataContract]
public class Sample
{
    [DataMember]
    public string Name { get; set; }
}

public string ShowMessage(Sample p, string Username, string Password)
{
    return p.Name.ToString() + " - " + "Correct"; //Error line
}

在客戶上:

[ServiceContract()]
public interface IGetMessage
{
    [OperationContract()]
    string ShowMessage(Sample p, string Username, string Password);
}

[DataContract()]
public class Sample
{
    [DataMember]
    public string Name { get; set; }

}

private void button1_Click(object sender, EventArgs e)
{
    Sample p1 = new Sample();
    p1.Name = "ALEX";

    BasicHttpBinding myBinding = new BasicHttpBinding();

    EndpointAddress myEndpoint = new EndpointAddress("http://MYURL/GetMessage.svc");

    using (var myChannelFactory = new ChannelFactory<IGetMessage>(myBinding, myEndpoint))
    {
        IGetMessage client = null;

        try
        {
            client = myChannelFactory.CreateChannel();

            MessageBox.Show(client.ShowMessage(p1, "abc","123"));

            ((ICommunicationObject)client).Close();
            myChannelFactory.Close();
        }
        catch
        {
            (client as ICommunicationObject)?.Abort();
        }
    }

}

如果我將客戶端添加為“服務參考”,則可以完美運行。 我可以收到“ ALEX-正確”消息。

當我在WcfTestClient.exe上進行測試時,它可以完美運行。

但是,在上述代碼的Winform上使用時,我遇到了問題。 當我檢查WcfServer跟蹤日志和消息日志時;

System.NullReferenceException-對象引用未設置為對象的實例。 行號:22

第22行:主機的GetMessage.cvs.cs文件上的p.Name.ToString()

我認為,主機上沒有問題。 問題是客戶端。

我想問你在客戶方面我是怎么做的?

問候。

如評論中所述,要解決此問題,您只需將名稱空間屬性添加到ServiceContract和DataContract。 確保客戶端和服務器之間的名稱空間相同。 我們應該這樣做的原因是在序列化和反序列化期間發生錯誤,因此必須確保服務協定和數據協定在服務器和客戶端之間具有一致的名稱空間。
這是我的示例(在服務器和客戶端上都添加此功能。)

    [ServiceContract(Namespace ="http://mydomain")]
    public interface IGetMessage
    {
        [OperationContract]
        string ShowMessage(Sample p, string Username, string Password);
    }

    [DataContract(Namespace = "http://mydomain")]
    public class Sample
    {
        [DataMember]
        public string Name { get; set; }
}

結果。
在此處輸入圖片說明
請隨時告訴我是否有什么我可以幫助的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM