Calling a Web api from another Web api

58k views Asked by At

Is it somehow possible to make a Web api that calls another web api?

I am using the code below to access a web api from my web api, but it never return from the call. If I use the code from a console app, it is working fine.

public void DoStuff(){
    RunAsync().Wait();
}

public static async Task RunAsync(){
using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:53452/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // HTTP GET
    HttpResponseMessage response = await client.GetAsync("umbraco/api/Member/Get?username=test");
    if (response.IsSuccessStatusCode)
    {
        string user = await response.Content.ReadAsAsync<string>();
    }

}
2

There are 2 answers

2
Propeus On BEST ANSWER

I also went through the same problem, after much research I discovered that the await operator does not stop the work if the HttpClient returns error 500.
To work around the problem I used Task.Wait().

var response = client.GetAsync ("umbraco/api/Member/Get?username=test");
response.Wait ();

I hope this helps others.

5
Gerald Davis On

Yes you can make a call to a remote web api within the action method of a web api controller.

Lets eliminate the obvious first.

If you set a breakpoint at the start of this action method it is getting hit right? If not then the issue lies in the routing not the action method.

If you set a breakpoint at the if statement does it get hit or is the client.GetAsync() call never returning?

If you haven't done already you may wish to use a tool like fiddler (http://www.telerik.com/fiddler) to compare the request & response from a working use of the api and this broken one. I know you said it is identical to a working implementation but I have found fiddler invaluable to verify exactly what is being sent "on the wire".