I am trying to call web api endpoint that is under same website using HttpClient.
My current iis setup is like below -
Main Website
- Application1
- WebApiApp
From Application1 I am trying to call web api controller that is in WebApiApp using HttpClient. If I specify the full url for m_service in below code it works -
using (HttpResponseMessage serviceResponse = await Client.GetAsync(new Uri(m_service + serviceEndPoint), HttpCompletionOption.ResponseHeadersRead))
{
return CreateResponse(serviceResponse);
}
Since this application is under the same website I want to use relative path to get the data from web api. The reason I am trying to do that is, this website runs on multiple webservers and is using network load balancer. Using full url for WebApiApp controller adds additional overhead of going through the load balancer. I would like to access the web api service on the same server.
Let me know if you need more details.Thanks for you help!
You must provide base address for HTTP request to work (i thought you had it in place). Just a relative URI is not a valid URL.
It does not matter if API is under same site, Web client will need full URL for a request. So in your case, you can set localhost in base address. Here's a sample code from http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client.
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
// code removed
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
// do something
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With