Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
708 views
in Technique[技术] by (71.8m points)

c# - 'System.Net.HttpWebRequest' does not contain a definition for 'GetRequestStream'

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 https://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);
    }
}

but for some reason Visual Studio is flagging GetRequestStream() with an error message:

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?)

Any thoughts on why this would be happening? I have already imported the System.Net package.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))
{
    // ...
}

Edit: 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()
{
    // ...
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...