2010-09-22 38 views
0

我目前正在研究WPF中設計的一組連接到一組Web服務的軟件。 web服務是在App.config定義:我的應用程序的端點:.NET WebServices連接問題

<endpoint address="http://localhost:52870/WebServices/Service.svc" 
    behaviorConfiguration="VanguardWebServiceBehavior" binding="wsHttpBinding" 
    bindingConfiguration="WSHttpBinding_IService" contract="WebServices.IService" 
    name="WSHttpBinding_IService"> 

,並在的applicationSettings:

<applicationSettings> 
<MyApp.Properties.Settings> 
    <setting name="PrimaryRS" serializeAs="String"> 
    <value>http://localhost:50563/</value> 
    </setting> 
    <setting name="PrimaryWS" serializeAs="String"> 
    <value>http://localhost:52870/WebServices/Service.svc</value> 
    </setting> 
    <setting name="SecondaryWS" serializeAs="String"> 
    <value>http://localhost:52870/WebServices/Service.svc</value> 
    </setting> 
</MyApp.Properties.Settings> 
</applicationSettings> 

這工作得很好,只要Web服務都可以訪問,但是當Web服務不能訪問應用程序崩潰。我想知道是否無論如何都要捕獲WebServices無法訪問時引發的異常,並且只需在某種斷開狀態下打開應用程序,以便任何內容都不可編輯。

由於提前,

帕特里克

回答

1

所以我終於發現這個問題發生了什麼。

要在加載應用程序時捕獲EndpointNotFoundException,初始連接的所有try/catch邏輯必須位於App.xaml.cs中,而不是位於MainPage.xaml.cs中。

我在MainPage.xaml.cs中有自動登錄信息和WebService連接件,並且在那裏沒有發現錯誤。將登錄和WebService連接移出MainPage.xaml.cs並移入App.xaml.cs後,我能夠輕鬆捕獲WebService連接失敗。

希望這可以幫助別人。

1

從你的配置,它看起來好像你使用WCF - 對嗎?

在這種情況下,基本上只是包裝你的Web服務調用在try...catch塊:

try 
{ 
    WebServiceClient client = new WebServiceClient(); 
    client.CallSomeMethod(); 
} 
catch(EndpointNotFoundException exc) 
{ 
    // endpoint not found --> webservice is not up and running 
} 
..... 
catch(CommunicationException exc) 
{ 
    // base WCF exception - for things like config errors etc. 
} 

在這種情況下,你可以捕獲到可能發生,默默地繼續工作的具體例外,與消息呈現給用戶盒子,或者你想在這種情況下做的任何事情。

幾乎所有的WCF例外都是CommunicationException(請參閱MSDN documentation)的後代 - 因此應該關注大多數WCF錯誤。

如果您想對發回錯誤的服務作出反應,您可能還想趕上FaultException(在CommunicationException之前) - 這些錯誤可能是服務器上的執行可能造成的錯誤(例如無法連接到數據庫或後端或其他)。

+0

感謝您的快速響應,但是我所有的WebService調用都是按照您的建議打包的。我收到的異常是XAMLParseException,它出現在我編寫的任何C#代碼之前。我添加了「拋出新的異常();」在我申請的最初階段確定這一點。 – 2010-09-22 16:51:32