我已经挣扎了一段时间,但我就是无法完成这项工作。我正在尝试通过使用“某种”异步等待将 json 字符串下载到我的 Windows Phone 8 应用程序。
我正在使用Matthias Shapiro 的有前途的解决方案。
HttpExtensions.cs
public static class HttpExtensions
{
public static Task<Stream> GetRequestStreamAsync(this HttpWebRequest request)
{
var taskComplete = new TaskCompletionSource<Stream>();
request.BeginGetRequestStream(ar =>
{
Stream requestStream = request.EndGetRequestStream(ar);
taskComplete.TrySetResult(requestStream);
}, request);
return taskComplete.Task;
}
public static Task<HttpWebResponse> GetResponseAsync(this HttpWebRequest request)
{
var taskComplete = new TaskCompletionSource<HttpWebResponse>();
request.BeginGetResponse(asyncResponse =>
{
try
{
HttpWebRequest responseRequest = (HttpWebRequest)asyncResponse.AsyncState;
HttpWebResponse someResponse = (HttpWebResponse)responseRequest.EndGetResponse(asyncResponse);
taskComplete.TrySetResult(someResponse);
}
catch (WebException webExc)
{
HttpWebResponse failedResponse = (HttpWebResponse)webExc.Response;
taskComplete.TrySetResult(failedResponse);
}
}, request);
return taskComplete.Task;
}
}
public static class HttpMethod
{
public static string Head { get { return "HEAD"; } }
public static string Post { get { return "POST"; } }
public static string Put { get { return "PUT"; } }
public static string Get { get { return "GET"; } }
public static string Delete { get { return "DELETE"; } }
public static string Trace { get { return "TRACE"; } }
public static string Options { get { return "OPTIONS"; } }
public static string Connect { get { return "CONNECT"; } }
public static string Patch { get { return "PATCH"; } }
}
还有我的 MainPageViewModel.cs
protected override void OnActivate()
{
base.OnActivate();
GetSessions();
}
private async void GetSessions()
{
var result = await GetMyData("http://localhost/api/MyData");
}
public async Task<string> GetMyData(string urlToCall)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlToCall);
request.Method = HttpMethod.Get;
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
using (var sr = new StreamReader(response.GetResponseStream()))
{
return sr.ReadToEnd();
}
}
一旦它达到“HttpWebResponse someResponse = (HttpWebResponse)responseRequest.EndGetResponse(asyncResponse);”,我就会得到一个 WebException:
“System.Net.WebException:远程服务器返回错误:未找到”
当我深入研究时,我注意到这个错误不是实际错误。当我检查 HttpExtensions 类的 GetResponseAsync 方法中的“asyncResponse”时,我注意到错误:
“AsyncWaitHandle = 'asyncResponse.AsyncWaitHandle' 引发了 'System.NotSupportedException' 类型的异常”
我不知道如何完成这项工作。是我做错了什么吗?