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

标签 c# httpwebrequest win-universal-app definition windows-10-universal

我在 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/

相关文章:

c# - Comparer<T> 类有什么用?

c# - NHibernate 级联删除

c# - 从 C# 启动浏览器并填写用户名和密码

c# - 如何获取 HTTP Web 请求以返回完整源代码

c# - 如何在 UWP 上使用通知中心?

c# - 图形性能改进/GDI 替代方案?

c# - C# 中的结构与类 - 请解释行为

c# - 检查URL是否存在-HTTP请求始终返回异常

c# - Xamarin Form - 如何在 UWP 中以 PDF 或 JPEG 格式存储图像

flash - 如何在 Windows 通用应用程序中使用 Adob​​e Flash