1
我能夠異步消費服務象下面這樣:如何使用Web服務異步
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;
}
}
我打電話從ViewModel類的PostMethodResponse()函數(這是在模型類)。我能夠在GetResponseCallback函數中獲得響應,但是如何將該響應返回到ViewModel,然後返回到View(前端.xaml)。爲了獲得響應,我們可以觸發一個事件GetResponseCallback函數,然後捕獲ViewModel類並啓動ViewModel同一事件並捕獲它,但這是一種不正確的方式。
請幫我理解MVVM架構調用Web服務。
在此先感謝。
這都無關MVVM。這是關於事件的基本理解和C#中的異步編程 – 2011-12-15 11:34:23
每當有人輸入「throw ex」時,一隻小貓就會死亡。 – 2011-12-15 11:38:55