gpt4 book ai didi

c# - WebRequest 不包含 Windows 10 通用应用程序的 'GetResponse' 的定义

转载 作者:行者123 更新时间:2023-11-30 23:29:11 30 4
gpt4 key购买 nike

我在 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()

这是错误的图像: 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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com