2012-10-10 24 views
1

我想用原始消息使用WCF服務。如何在原始消息中使用WCF服務?

1)WCF服務代碼:

[DataContract] 
public class Person 
{ 
    [DataMember] 
    public int Id { get; set; } 

    [DataMember] 
    public string FirstName { get; set; } 

    [DataMember] 
    public string LastName { get; set; } 
} 

public static List<Person> CreateEmployees() 
{ 
    List<Person> lstPersons = new List<Person>() 
    { 
     new Person { Id = 1, FirstName = "Andrey", LastName = "Andreyev" }, 
     new Person { Id = 2, FirstName = "Sergey", LastName = "Sergeyev" } 
    }; 

    return lstPersons; 
} 

[ServiceContract] 
public interface ITestService 
{ 
    [OperationContract(Action = TestService.RequestAction, ReplyAction = TestService.ReplyAction)] 
    Message GetPersonById(Message id); 
} 

public class TestService : ITestService 
{ 
    public const String ReplyAction = "http://localhost:4249/Message_ReplyAction"; 
    public const String RequestAction = "http://localhost:4249/Message_RequestAction"; 

    public Message GetPersonById(Message id) 
    { 
     string firstName = Employees.CreateEmployees().First(e => e.Id == id.GetBody<int>()).FirstName; 
     Message response = Message.CreateMessage(id.Version, ReplyAction, firstName); 
     return response; 
    } 
} 

2)客戶端代碼:

static void Main(string[] args) 
{ 
    TestServiceClient client = new TestServiceClient(); 
    String RequestAction = "http://localhost:4249/Message_RequestAction"; 
    int value = 1; 
    Message request = Message.CreateMessage(MessageVersion.Default, RequestAction, value); 
    Message reply = client.GetPersonById(request); 
    string firstName = reply.GetBody<string>(); 

    Console.WriteLine(firstName); 
    client.Close(); 
} 

當我運行與客戶端:int值= 1周的一切工作正常。但是,當我使用:int值= 2,我得到以下錯誤:

Error in line 1 position 276. Expecting element 'string' from namespace 'http://schemas.microsoft.com/2003/10/Serialization/'.. Encountered 'Element' with name 'Fault', namespace 'http://www.w3.org/2003/05/soap-envelope'.

在行:

string firstName = reply.GetBody<string>(); 

服務已啓動,我已經加入到「添加服務引用服務引用...「在VS2008中。我使用.NET Framework 3.5。

我不知道爲什麼我得到這個錯誤。

非常感謝您的幫助。

Goran

+0

你能發佈完整的信息嗎?你可以使用wcf tester或者mse service tester來獲得這些信息 - 它告訴你這是一個錯誤,你的代碼不能處理這個客戶端。 – Chris

+0

如果你的意思是在WCF測試客戶端上,我不能使用它,因爲在工具提示中有紅色的圖標帶有白色的感嘆號和消息:「WCF測試客戶端不支持此操作,因爲它使用類型System.ServiceModel.Channels。 。消息 – tesicg

回答

1

那麼,你會得到一個SOAP錯誤。嘗試記錄消息(使用Fiddler,使用WCF日誌記錄,或者通過從客戶端的服務器獲取的消息中讀取Message.GetReaderAtBodyContents),然後查看錯誤實際所說的內容。確保你打開服務器端的IncludeExceptionDetailInFaults。

+0

我跑提琴手和客戶端的代碼,但在提琴手什麼都沒有發生 – tesicg

+0

另外,我寫了這個:信息回覆= client.GetPersonById(請求); XmlDictionaryReader讀卡器= reply.GetReaderAtBodyContents(); 字符串的firstName = ();讀者是:reader = {Element,Name =「Fault」} – tesicg

+0

我的意思是,在你完成「XmlDictionaryReader reader = reply.GetReaderAtBodyContents();」後,從「reader 「然後將其記錄到控制檯,你看到了什麼?它應該告訴你服務器上發生了什麼,如果服務器有IncludeExcept ionDetailInFaults打開) –