WebRequest不包含Windows 10 Universal App的“GetResponse”定义

我在GitHub上下载一个控制台应用程序,工作正常。 但我想将此C#控制台应用程序转换为通用Windows 10应用程序。

Visual Studio上的错误Web Request does not contain a definition for...

这是代码:

  private AccessTokenInfo HttpPost(string accessUri, string requestDetails) { //Prepare OAuth request WebRequest webRequest = WebRequest.Create(accessUri); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Method = "POST"; byte[] bytes = Encoding.ASCII.GetBytes(requestDetails); webRequest.ContentLength = bytes.Length; using (Stream outputStream = webRequest.GetRequestStream()) { outputStream.Write(bytes, 0, bytes.Length); } using (WebResponse webResponse = webRequest.GetResponse()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AccessTokenInfo)); //Get deserialized object from JSON stream AccessTokenInfo token = (AccessTokenInfo)serializer.ReadObject(webResponse.GetResponseStream()); return token; } } 

基本上我在这3个函数上得到一个错误:

 webRequest.ContentLength webRequest.GetRequestStream() webRequest.GetResponse() 

这是错误的图像: 图像有错误:“不包含定义”

有条件的评论:我在GitHub上读了几个类似的问题,似乎我需要创建一个像这样的AsyncResult

这是一些类似问题的答案(我不知道如何将其应用于我的问题):

  /** In case it is a Windows Store App (and not WPF) there is no synchronous GetResponse method in class WebResponse. You have to use the asynchronous GetResponseAsync instead, eg like this: **/ using (var response = (HttpWebResponse)(await request.GetResponseAsync())) { // ... } 

提前致谢!

在您链接的答案中,有一个评论与实际答案:

如果它是Windowsapp store应用程序(而不是WPF),WebResponse类中没有同步的GetResponse方法

您必须在UWP应用程序中使用异步方法,因为它们不再具有同步cals以提高用户界面性能(不再挂起UI,因为它在同一个线程上执行Web请求)

你的代码应该是

 HttpWebResponse response = await webrequest.GetResponseAsync(); 

以下是有关async / await以及如何使用它的更多信息: https : //msdn.microsoft.com/en-us/library/hh191443.aspx