Question

I'm communicating with my server with the following code,

private void Save_Click(object sender, RoutedEventArgs e)
    {
        var request = HttpWebRequest.Create(url) as HttpWebRequest;
        request.Method = "POST";
        request.BeginGetResponse(new AsyncCallback(GotResponse), request);

    }
private void GotResponse(IAsyncResult asynchronousResult)
    {
      try
       {
        string data;
        HttpWebRequest myrequest = (HttpWebRequest)asynchronousResult.AsyncState;
        using (HttpWebResponse response = (HttpWebResponse)myrequest.EndGetResponse(asynchronousResult))
        {
            System.IO.Stream responseStream = response.GetResponseStream();
            using (var reader = new System.IO.StreamReader(responseStream))
            {
                data = reader.ReadToEnd();
            }
            responseStream.Close();
        }
        this.Dispatcher.BeginInvoke(() =>
        {
            MessageBox.Show(data);
        });
      }
      catch (Exception e)
        {
            var we = e.InnerException as WebException;
            if (we != null)
            {
                var resp = we.Response as HttpWebResponse;
                var code = resp.StatusCode;
                this.Dispatcher.BeginInvoke(() =>
                    {
                        MessageBox.Show("Message :" + we.Message + " Status : " + we.Status);
                    });
            }
            else
                throw;
        }
    }

I'm giving date and amount as my input value,it is url encoded. If all my data's are valid then everything works fine. And so my server will give the data as

{
 "code":0,
 "message":"Success",
 "data":{
         "date":xxxx,
         "amount":123
        }
}

But in case if give an invalid value,(For eg: abcd for 'amount'), then my server would reply as

{
 "code":2,
 "message":"Invalid value passed"
}

In this case, after Executing the line

using (HttpWebResponse response = (HttpWebResponse)myrequest.EndGetResponse(asynchronousResult))

It jumps to catch, and it display

Message:The remote server returned an error:NotFound. Status:UnKnown Error

Required Solution: It should fetch the result as it did in the previous case. What sholud i do to fix it?

Was it helpful?

Solution

Well presumably the HTTP status code is 404. You're already accessing the response in your error code though - all you need to do is try to parse it as JSON, just as you are in the success case, instead of using we.Message to show an error message. You should probably be ready for the content to either be empty or not include valid JSON though, and only do this on specific status codes that you expect to still return JSON.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top