问题描述
我是新来的两个C#和Windows Phone,我试图做一个小的应用程序,执行一个JSON请求。我下面这个职位的例子
I am new to both C# and Windows phone and am trying to make a small app that performs a JSON request. I am following the example in this post http://stackoverflow.com/a/4988809/702638
我当前的代码是这样的:
My current code is this:
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()
一个错误信息:
错误CS1061:'System.Net.HttpWebRequest不包含'GetRequestStream',没有扩展方法
A
定义'GetRequestStream接受式
'System.Net.HttpWebRequest'的第一个参数可以找到(是否缺少使用
指令或程序集引用?)
这是为什么这会是发生什么想法?我已经导入了<$ C $ C> System.Net 包。
Any thoughts on why this would be happening? I have already imported the System.Net
package.
推荐答案
HttpWebRequest的的不WP8拥有的 GetRequestStream 或 GetRequestStreamAsync 的。最好的办法是创建一个任务并等待其上,像这样:使用(VAR流
HttpWebRequest doesn't have a GetRequestStream or GetRequestStreamAsync in WP8. Your best bet is to create a Task and await on it, like so:
using (var stream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null))
{
// ...
}
编辑:正如您所提到的,你是新的C#,你需要让你的登录方法是异步使用的await关键字:
as you've mentioned that you're new to C#, you would need to have your login method be async to use the await keyword:
public async Task<string> LoginAsync()
{
// ...
}
呼叫者登录需要使用电话时的await关键字:
Callers to login would need to use the await keyword when calling:
string result = await foo.LoginAsync();
下面是关于这个问题的好底漆:的
Here's a good primer on the subject: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
这篇关于“System.Net.HttpWebRequest'不包含'GetRequestStream”的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!