本文介绍了“System.Net.HttpWebRequest"不包含“GetRequestStream"的定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C# 和 Windows 手机的新手,正在尝试制作一个执行 JSON 请求的小应用程序.我正在遵循这篇文章中的示例 https://stackoverflow.com/a/4988809/702638

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);
    }
}

但出于某种原因,Visual Studio 正在标记 GetRequestStream() 并显示一条错误消息:

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

错误 CS1061:System.Net.HttpWebRequest"不包含'GetRequestStream' 的定义并且没有扩展方法'GetRequestStream' 接受类型的第一个参数可以找到System.Net.HttpWebRequest"(您是否缺少使用指令或程序集引用?)

关于为什么会发生这种情况的任何想法?我已经导入了 System.Net 包.

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

推荐答案

HttpWebRequest 在 WP8 中没有 GetRequestStreamGetRequestStreamAsync.最好的办法是创建一个任务并等待它,如下所示:

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();

这里有关于这个主题的很好的入门:http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

Here's a good primer on the subject: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

这篇关于“System.Net.HttpWebRequest"不包含“GetRequestStream"的定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 12:03