質問

I'm writing a Windows Phone 8 application that is designed to work online and offline. To do this it needs to be able to check for an internet connection. This is fine if there's no connection, or if there is a connection, but if the user is connected to a wifi hotspot and they haven't authenticated, then I need to return a 'no connection' status. However, even with a try catch it seems impossible to catch the System.Net.WebException error using either WebClient or HttpWebRequest. I've searched all over for solutions but none seem to work - any help would be appreciated.

Here's my connection check code:

public async Task<bool> tskbooCheckConnectionSimpleNoQueue()
    {
        bool booHasConnection = false;
        bool isNetwork = NetworkInterface.GetIsNetworkAvailable();
        if (!isNetwork)
        {
            booHasConnection = false;
            IsolatedStorageSettings.ApplicationSettings["booHasConnection"] = false;
            return booHasConnection;
        }
        else
        {
            //actually check connection
            WebClient wcConnectionCheck = new WebClient();
            string strData = "";
            string strConnectionCheck = "https://urltocheckconnection.com/connectioncheckmethod"; 
            try
            {
                strData = await wcConnectionCheck.DownloadStringTaskAsync(new Uri(strConnectionCheck)); //exception thrown here
                if (strData.ToString().Contains("success"))
                {
                    booHasConnection = true;
                    IsolatedStorageSettings.ApplicationSettings["booHasConnection"] = true;
                    return booHasConnection;
                }
                else
                {
                    booHasConnection = false;
                    IsolatedStorageSettings.ApplicationSettings["booHasConnection"] = false;
                    return booHasConnection;
                }
            }
            catch (WebException ex)
            {
                booHasConnection = false;
                IsolatedStorageSettings.ApplicationSettings["booHasConnection"] = false;
                return booHasConnection;
            }
        }
    }
役に立ちましたか?

解決

Sounds like you have catch handled exceptions turned on.

In visual studio, click the 'Debug' menu and select 'Exceptions'.

Under the 'Common Language Runtime Exceptions' item, untick the 'Thrown' column.

Your debugger will no longer break, and the exception will be caught.

enter image description here

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top