0

I have to call method using REST service as I got some solution from material but getting error in await

public static Task RunAsync()
{
    string pathValue = WebConfigurationManager.AppSettings["R2G2APIUrl"];
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(pathValue);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
                    new MediaTypeWithQualityHeaderValue("application/json"));

        var id = "12421";
        HttpResponseMessage response = await client.GetAsync("api/products/1");
        var jobid = new Jobs() { Job_ID = id};
        response = await client.PostAsJsonAsync("api/products", jobid);
        if (response.IsSuccessStatusCode)
        {
            Uri gizmoUrl = response.Headers.Location;
        }
    }
}
static void Main()
{
    RunAsync().Wait();
}

await is not exist in current context as I am using vs2010 but is there any other solution for this?

tereško
  • 58,060
  • 25
  • 98
  • 150
Dhara
  • 1,914
  • 2
  • 18
  • 37

2 Answers2

1

Instead of using await, you can use ContinueWith.

public static Task RunAsync()
{
    string pathValue = WebConfigurationManager.AppSettings["R2G2APIUrl"];
    var client = new HttpClient()
            client.BaseAddress = new Uri(pathValue);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
            var id = "12421";
        return client.GetAsync("api/products/1").ContinueWith(_ =>
    {
        var jobid = new Jobs() { Job_ID = id };
        return client.PostAsJsonAsync("api/products", jobid)
       .ContinueWith(responseTask =>
        {
          var gizmoUrl = responseTask.Result.IsSuccessStatusCode ?
                                        responseTask.Result.Headers.Location : null;
        });
    });
}

Note you have some redundancies in your code, like issuing a GetAsync request and doing nothing with the returned HttpResponseMessage.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • m gettin error `Cannot access a disposed object.Object name: 'System.Net.Http.HttpClient'.` – Dhara Oct 15 '15 at 04:50
  • @debin You're right, I forgot to remove the `using` statement. Fixed it now. – Yuval Itzchakov Oct 15 '15 at 05:04
  • ah thnku so muchh..a little doubt..i will call this method as `RunAsync().Wait()` right? now I want to call a particular method which is in that `pathvalue`..any idea? – Dhara Oct 15 '15 at 05:35
  • @debin Sorry, I didn't understand your question. What is `pathvalue`? – Yuval Itzchakov Oct 15 '15 at 05:46
  • I am fetching URL from webconfig that is `pathvalue` – Dhara Oct 15 '15 at 05:48
  • @debin Ok, and what problem have you encountered? – Yuval Itzchakov Oct 15 '15 at 06:04
  • sorry m gettin err again of `responseTask.Result.IsSuccessStatusCode 'responseTask.Result' threw an exception of type 'System.AggregateException` I know its certificate related..but how to solve it??i dn want to export certificate – Dhara Oct 15 '15 at 06:28
  • What is the inner exception? – Yuval Itzchakov Oct 15 '15 at 06:32
  • the error is `{"An error occurred while sending the request."} and {"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."}` – Dhara Oct 15 '15 at 06:33
  • yah got it..jus last question..what this method will return??? because m calling it like `public bool restfunc(string id) { RunAsync(id).Wait(); return true; }`so how to save the result or check what is the return value? – Dhara Oct 15 '15 at 07:01
0

Maybe you could just use the .Result of the async operation.

     public static Task RunAsync()
     {
        string pathValue = WebConfigurationManager.AppSettings["R2G2APIUrl"];
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(pathValue);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            var id = "12421";
            HttpResponseMessage response = client.GetAsync("api/products/1").Result;
            var jobid = new Jobs() { Job_ID = id };
            response = client.PostAsJsonAsync("api/products", jobid).Result;
            if (response.IsSuccessStatusCode)
            {
                Uri gizmoUrl = response.Headers.Location;
            }
        }
    }
t.enix
  • 156
  • 3