Reputation: 1
I want to consume my WebAPI from my WCF Service, i.e. I want my WCF Service to call a web API. I have searched on the internet a lot, but all the forums are concentrating on calling WCF from web API, though I need the reverse of that.
Is this possible to do?
Upvotes: 0
Views: 5935
Reputation: 5732
Sure you can. Just use a normal HttpClient like you would do in any .NET application:
// consider caching or getting the httpclient instance from a factory
var client = new HttpClient();
//Api Base address
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending a GET request to endpoint api/products/1
HttpResponseMessage response = await client.GetAsync("api/person/1");
if (response.IsSuccessStatusCode)
{
//Getting the result and mapping to a Product object
Person person = await response.Content.ReadAsAsync<Person>();
}
Since you didn't specified, the above code is for a GET request. You can find more examples here: Calling a Web API From a .NET Client in ASP.NET Web API 2 (C#)
Upvotes: 2