WebRequest does not contain a definition for 'GetResponse' for Windows 10 Universal App

家住魔仙堡 提交于 2019-12-08 01:51:00

问题


I download a Console Application on GitHub and works fine. But I want to translate this C# Console Application to a Universal Windows 10 Application.

The error on Visual Studio: Web Request does not contain a definition for...

This is the code:

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

basically I get an error on this 3 functions:

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

This is an image of the error: Image with error: "Does not contain a definition"

Aditional Comments: I read a few similar problems on GitHub and it seems I need to create a AsyncResult like this

This is the answer for some similar question (I dont know how to apply this to my problem):

  /**  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()))
{
    // ...
}

Thanks in advance!


回答1:


in the answer you linked there is a comment with the actual answer:

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 async methods in UWP apps since they don't have synchronous cals anymore to improve user interface performance (no more hanging UI because it's doing a web request on the same thread)

your code should be in the form of

HttpWebResponse response = await webrequest.GetResponseAsync();

Here is some more info on async/await and how to use it: https://msdn.microsoft.com/en-us/library/hh191443.aspx



来源:https://stackoverflow.com/questions/35619622/webrequest-does-not-contain-a-definition-for-getresponse-for-windows-10-univer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!