Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll

I'm developing a Windows Phone 8 application. I am getting this error when I try to run my app:

My error description

An exception of type 'System.Net.WebException' occurred in System.Windows.ni.dll but was not handled in user code.

My code

private async void buttonStringGet_Click_1(object sender, RoutedEventArgs e)
{
    JsonWebAsync.JsonWebClient client = new JsonWebAsync.JsonWebClient();
    var resp = await client.DoRequestAsync("myurl");
    string result = resp.ReadToEnd();
    resultText.Text = result;
}
like image 862
faroke moahmed Avatar asked Nov 11 '13 10:11

faroke moahmed


1 Answers

For whatever reason, it looks like the remote web server is responding with 404 Not Found. Maybe the server is doing the right thing. If so, you're application is going to need to deal with this response in a sensible way. Maybe it isn't doing the right thing, and you have a bug in your server component to fix. :-)

I'd approach solving the application crash in two different ways.

First, let's handle this error so the application doesn't crash. As an example, we'll just populate the resultText control with some details about the error. As we have no details about what the request is supposed to do or what the response looks like, there isn't much more robust error handling that can be discussed right now. Keep in mind that networks calls don't always work, so you're going to need some error handling even if you address the second point, below.

private async void buttonStringGet_Click_1(object sender, RoutedEventArgs e)
{
    JsonWebAsync.JsonWebClient client = new JsonWebAsync.JsonWebClient();

    string result;

    try
    {
        var resp = await client.DoRequestAsync("myurl");
        result = resp.ReadToEnd();
    }
    catch (WebException ex)
    {
         // generic error handling
         result = string.Format("Could not get data. {0}", ex);
    }

    resultText.Text = result;
}

Second, let's try to avoid the error in the first place. Let's make sure the request the client is sending makes sense. You could add some instrumentation code to make sure that whatever gets used instead of "myurl" is sensible.

private async void buttonStringGet_Click_1(object sender, RoutedEventArgs e)
{
    JsonWebAsync.JsonWebClient client = new JsonWebAsync.JsonWebClient();

    string requestUrl = ComputeRequestUrl(); // I assume this code exists somewhere.
    System.Diagnostics.Debug.WriteLine("Sending request for {0}", requestUrl);
    var resp = await client.DoRequestAsync(requestUrl);
    string result = resp.ReadToEnd();
    resultText.Text = result;
}

Now, when you run a debug build with a debugger attached, you should be able to see the tracing output in the Output window of Visual Studio when you pick the Debug stream.

like image 168
chwarr Avatar answered Oct 23 '22 22:10

chwarr