我对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正在使用错误消息标记GetRequestStream():
错误CS1061:'System.Net.HttpWebRequest‘不包含'GetRequestStream’的定义,也找不到接受'System.Net.HttpWebRequest‘类型的第一个参数的扩展方法'GetRequestStream’(您缺少使用指令还是程序集引用?)
对为什么会发生这种事有什么想法吗?我已经导入了System.Net包。
发布于 2013-01-15 18:14:20
HttpWebRequest在WP8中没有GetRequestStream或GetRequestStreamAsync。您最好的选择是创建一个任务并等待它,如下所示:
using (var stream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null))
{
// ...
}编辑:正如您已经提到的,您是C#新手,您需要让您的登录方法是异步的,才能使用等待关键字:
public async Task<string> LoginAsync()
{
// ...
}调用登录的调用者在调用以下命令时需要使用等待关键字:
string result = await foo.LoginAsync();这里有一个很好的主题入门:http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
https://stackoverflow.com/questions/14344029
复制相似问题