1

My problem

I have my Universal Windows Application and i want work with rest api. I always get error CS 4032 in this :

httpResponseBody = await httpClient.GetStringAsync(requestUri);

Like you can't call that method when it is not async.

Whole code

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Net;
using Windows.Web.Http;
namespace UniversalCA
{

   public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            Send();             

        }

        public string Send()
        { 
            HttpClient httpClient = new HttpClient();
            Uri requestUri = new Uri("http://restapic.azurewebsites.net/WebForm1.aspx?func=dd&hodn=WW");
            HttpResponseMessage httpResponse = new HttpResponseMessage();
            string httpResponseBody = "";
            try
            {
                httpResponseBody = await httpClient.GetStringAsync(requestUri);
            }
            catch (Exception ex)
            {
                httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message;
            }
            string tt = httpResponseBody.Split('>')[1].Split('<')[0];
            return httpResponseBody;

        }
    }
}
Sir Rufo
  • 16,671
  • 2
  • 33
  • 66
Ivan Čík
  • 19
  • 1

2 Answers2

1

The problem is that you cannot use await keyword inside a not async function. Your Send function does not have async keyword in declaration. Adding async keyword will solve the problem

public async Task<string> Send()
Ruben Vardanyan
  • 1,258
  • 10
  • 19
0

Just To add to @Ruben Vardanyans answer.

simply: add using System.Threading.Tasks;

add Wait() keyword on your Send(); call

    public MainPage()
    {
        this.InitializeComponent();
        Send().Wait();             

    }

and finally on your Send() method add async Task<T>

  public async Task<string> Send()

Please check out this answer for calling an asynchronous method inside a constructor. Call asynchronous method in constructor?

do not use await Send(); for calling the method you will have a compiler error.

Community
  • 1
  • 1
Drew Aguirre
  • 309
  • 1
  • 12