我是C#和
Windows手机的新手,我试图制作一个执行
JSON请求的小应用程序.我在这个帖子
https://stackoverflow.com/a/4988809/702638中跟着这个例子
我当前的代码是:
public string login()
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(MY_URL);
httpWebRequest.ContentType = "text/plain";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string text = MY_JSON_STRING;
streamWriter.Write(text);
}
}
但由于某种原因Visual Studio正在标记GetRequestStream()并显示一条错误消息:
error CS1061: ‘System.Net.HttpWebRequest’ does not contain a
deFinition for ‘GetRequestStream’ and no extension method
‘GetRequestStream’ accepting a first argument of type
‘System.Net.HttpWebRequest’ Could be found (are you missing a using
directive or an assembly reference?)
有什么想法为什么会发生这种情况?我已经导入了System.Net包.
解决方法
HttpWebRequest在WP8中没有GetRequestStream或GetRequestStreamAsync.你最好的打算是创建一个任务并等待它,像这样:
using (var stream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream,request.EndGetRequestStream,null))
{
// ...
}
编辑:正如您所提到的那样,您刚刚开始使用C#,您需要将登录方法异步到使用await关键字:
public async Task<string> LoginAsync()
{
// ...
}
呼叫者在拨打电话时需要使用await关键字:
string result = await foo.LoginAsync();
这是一个很好的主题:http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx