I am able to consume a service asynchronously like below:
public void PostMethodResponse()
{
try
{
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(_url);
myRequest.Method = "POST";
myRequest.Headers["SOAPAction"] = _action;
myRequest.ContentType = "text/xml; charset=utf-8";
myRequest.Accept = "text/xml";
myRequest.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), myRequest);
}
catch (Exception ex)
{
throw ex;
}
}
private void GetRequestStreamCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult);
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(_postData);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
// Start the asynchronous operation to get the response
request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}
catch (Exception ex)
{
throw ex;
}
}
private void GetResponseCallback(IAsyncResult asynchronousResult)
{
try
{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
// Close the stream object
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse
response.Close();
_response = responseString;
}
catch (Exception ex)
{
_response = ex.Message;
}
}
I am calling the PostMethodResponse() function (which is in Model Class) from a ViewModel class. I am able get the response in GetResponseCallback function but how can i return that Response to ViewModel and then to View(Front End .xaml). To get the Response, We can fire an event GetResponseCallback function and then catch it ViewModel Class and Fire the same event ViewModel and Catch it View, But this is a not a right way.
Please help me in understanding the MVVM architecture call web services.
Thanks in advance.
Like this: