我一直在努力了一段時間,但我無法得到這項工作。我試圖通過使用'sort of'async await來下載一個json字符串到我的Windows Phone 8應用程序。我正在使用the promising solution of Matthias Shapiro。無法讓異步(異步等待)下載的JSON工作
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);」,我越來越a WebException:
「System.Net.WebException:遠程服務器返回錯誤:NotFound」
當我深入一點時,我注意到這個錯誤不是實際的錯誤。當我檢查在HttpExtensions類的GetResponseAsync方法裏面的「asyncResponse」我注意到該錯誤:
「AsyncWaitHandle =‘asyncResponse.AsyncWaitHandle’投擲‘System.NotSupportedException’類型的異常」
我沒有想法如何獲得這項工作。這是我做錯了什麼嗎?
奇怪的是,我使用完全相同,它的工作對我來說很好。你有沒有導入這個參考http://nuget.org/packages/Microsoft.Bcl.Async? – robertk 2013-03-04 12:55:09
我一直試圖使用或不使用這個軟件包,但都返回給我同樣的錯誤...當我嘗試這與一個在線的URL,它的作品'有時'...有一些與嘗試它本地?我當我用FireFox檢查URL時,我得到了我期望的結果......它太奇怪了...... – 2013-03-04 13:05:00
我現在看到了問題。由於模擬器正在使用虛擬機,因此您不能使用本地主機,因爲localhsot是手機而不是您的PC。看到這個解決方案:http://stackoverflow.com/questions/13149304/windows-phone-8-emulator-access-localhost – robertk 2013-03-04 13:06:39