0

I am trying to access Web API in C# Code. I have tried below code in .Net Framework 4.0 but its shows an error message as “task httpresponsemessage does not contain a definition for getawaiter”.Please check below code and advise how to resolve this issue.

Code:-

static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:9000/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            
            // HTTP GET
            HttpResponseMessage response = await client.GetAsync("api/products/1");
            if (response.IsSuccessStatusCode)
            {
                Product product = await response.Content.ReadAsAsync<Product>();
                Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
            }

            // HTTP POST
            var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
            response = await client.PostAsJsonAsync("api/products", gizmo);
            if (response.IsSuccessStatusCode)
            {
                Uri gizmoUrl = response.Headers.Location;

                // HTTP PUT
                gizmo.Price = 80;   // Update price
                response = await client.PutAsJsonAsync(gizmoUrl, gizmo);

                // HTTP DELETE
                response = await client.DeleteAsync(gizmoUrl);
            }
        }
    }
PPC2
  • 11
  • 1
  • what line number is the error – Andy Sep 10 '20 at 04:08
  • // HTTP GET HttpResponseMessage response = await client.GetAsync("api/products/1"); – PPC2 Sep 10 '20 at 04:11
  • Are you trying to use `System.Net.Http.Json.HttpClientJsonExtensions`? You should be using `Newtonsoft.Json` and `System.Net.Http.HttpClientExtensions` nuget package. – Andy Sep 10 '20 at 04:13
  • To Michael Randall's point, `GetAwaiter` was [introduced in .NET 4.5](https://apisof.net/catalog/System.Threading.Tasks.Task%3CTResult%3E.GetAwaiter()). – madreflection Sep 10 '20 at 04:18
  • Can you advise what is the alternate solution to access web api in C# using .Net Framework 4.0 ?? – PPC2 Sep 10 '20 at 04:23
  • Don't use async/await. Is there a reason you can't upgrade to 4.5? – madreflection Sep 10 '20 at 04:24
  • ok noted but what is the alternate solution to do in .net framework 4.0,if possible provide me example code – PPC2 Sep 10 '20 at 04:36
  • https://stackoverflow.com/questions/19423251/async-await-keywords-not-available-in-net-4-0 If there's an alternative, it's there, and all I had to do was Google ".net 4.0 async". – madreflection Sep 10 '20 at 04:40

1 Answers1

0

ok noted but what is the alternate solution to do in .net framework 4.0, if possible provide me example code

We can make use of the HttpWebRequest class available in System.Net namespace. Along with that Newtonsoft.Json library (available as a nuget package) is also required for serialization and deserialization of data.

Inline is a rewrite of the requirement with HttpWebRequest

static void Run()
{
    // HTTP GET
    var getRequest = WebRequest.Create("http://localhost:9000/api/products/1") as HttpWebRequest;
    getRequest.ContentType = "application/json;charset=UTF-8";
    getRequest.Method = "GET";

    HttpWebResponse getResponse = getRequest.GetResponse() as HttpWebResponse;

    if (getResponse.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = getResponse.GetResponseStream();
        using (StreamReader sr = new StreamReader(responseStream))
        {
                    
            var product = JsonConvert.DeserializeObject<Product>(sr.ReadToEnd());
            Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
        }
    }
    else
    {
        throw new Exception(getResponse.StatusDescription);
    }

    // HTTP POST
    var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
    var postRequest = WebRequest.Create("http://localhost:9000/api/products") as HttpWebRequest;
    postRequest.ContentType = "application/json;charset=UTF-8";
    postRequest.Method = "POST";

    Stream stream = postRequest.GetRequestStream();
    byte[] buffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(gizmo));
    stream.Write(buffer, 0, buffer.Length);
    HttpWebResponse postResponse = postRequest.GetResponse() as HttpWebResponse;

    if (postResponse.StatusCode == HttpStatusCode.OK)
    {
        //HTTP PUT
        string gizmoUrl = postResponse.Headers["Location"];
        var putRequest = WebRequest.Create(gizmoUrl) as HttpWebRequest;
        putRequest.ContentType = "application/json;charset=UTF-8";
        putRequest.Method = "PUT";

        gizmo.Price = 80; //Update price

        Stream putRequestStream = putRequest.GetRequestStream();
        byte[] putRequestBuffer = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(gizmo));
        stream.Write(buffer, 0, buffer.Length);
        HttpWebResponse putResponse = putRequest.GetResponse() as HttpWebResponse;

        //HTTP DELETE
        var deleteRequest = WebRequest.Create(gizmoUrl) as HttpWebRequest;
        deleteRequest.ContentType = "application/json;charset=UTF-8";
        deleteRequest.Method = "DELETE";
        HttpWebResponse deleteResponse = deleteRequest.GetResponse() as HttpWebResponse;
    }
    else
    {
        throw new Exception(postResponse.StatusDescription);
    }
}

Note: I have not tested the code from my end. There might be minor modification required if things do not work as intended. However the motive is to provide an insight into HttpWebRequest class which can full fill your requirement in .Net 4

Durga Prasad
  • 939
  • 10
  • 20