.NET WebServices Connectivity issue
I'm currently working on a piece of software designed in WPF that connects to a set of WebServices. The WebServices are defined in the app.config:endpoint of my application:
<endpoint address="http://localhost:52870/WebServices/Service.svc"
behaviorConfiguration="VanguardWebServiceBeh开发者_运维百科avior" binding="wsHttpBinding"
bindingConfiguration="WSHttpBinding_IService" contract="WebServices.IService"
name="WSHttpBinding_IService">
and in the 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>
This works fine, so long as the WebServices are accessible, however when the WebServices are not accessible the application crashes. I am wondering if there is anyway to catch the Exceptions that are thrown when the WebServices are not accessible, and simply open the application in some sort of Disconnected state, such that nothing is editable.
Thanks in advance,
Patrick
From your config, it looks as if you're using WCF - right?
In that case, basically just wrap your web service calls in try...catch
blocks:
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.
}
In this case, you can catch the specific exceptions that might happen and silently keep working, present the user with a message box, or whatever it is you want to do in this case.
Almost all WCF exceptions are descendants of CommunicationException
(see the MSDN documentation for it) - so catching that should take care of most WCF errors.
If you want to react to the service sending you errors back, you might also want to catch FaultException
(before CommunicationException
) - those would be the errors that the execution on the server may have caused (e.g. cannot connect to a database or backend or something).
So I finally found what was going on with this issue.
To catch the EndpointNotFoundException as the application is loading, all try/catch logic for the initial connection must be in the App.xaml.cs rather than in the MainPage.xaml.cs.
I had auto-login information and WebService connectivity pieces in the the MainPage.xaml.cs and the error was not being caught there. Upon moving the login and WebService connectivity out of the MainPage.xaml.cs and into the App.xaml.cs I am able to easily catch WebService connection failures.
Hope this helps someone else.
精彩评论