我在 GitHub 上下载了一个控制台应用程序并且工作正常。 但我想将此 C# 控制台应用程序转换为通用 Windows 10 应用程序。
Visual Studio 上的错误:Web 请求不包含...的定义
这是代码:
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()
这是错误的图像: Image with error: "Does not contain a definition"
其他评论: 我在 GitHub 上读到了一些类似的问题,似乎我需要创建一个像 this 这样的 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, e.g. like this: **/
using (var response = (HttpWebResponse)(await request.GetResponseAsync()))
{
// ...
}
提前致谢!
最佳答案
在您链接的答案中,有一 strip 有实际答案的评论:
In case it is a Windows Store App (and not WPF) there is no synchronous GetResponse method in class WebResponse
您必须在 UWP 应用中使用异步方法,因为它们不再具有同步调用来提高用户界面性能(不再有挂起的 UI,因为它在同一线程上执行 Web 请求)
您的代码应采用以下形式
HttpWebResponse response = await webrequest.GetResponseAsync();
以下是有关 async/await 及其使用方法的更多信息:https://msdn.microsoft.com/en-us/library/hh191443.aspx
关于c# - WebRequest 不包含 Windows 10 通用应用程序 'GetResponse' 的定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35619622/