WebRequest does not contain a definition for '

2019-05-28 05:26发布

问题:

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