How to call a WebAPI from Windows Service
Solution 1
You could use System.Net.Http.HttpClient. You will obviously need to edit the fake base address and request URI in the example below but this also shows a basic way to check the response status as well.
// Create an HttpClient instance
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8888/");
// Usage
HttpResponseMessage response = client.GetAsync("api/importresults/1").Result;
if (response.IsSuccessStatusCode)
{
var dto = response.Content.ReadAsAsync<ImportResultDTO>().Result;
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
Solution 2
You can install this NuGet package Microsoft ASP.NET Web API Client Libraries to your Windows Service project.
Here is a simple code snippet demonstrating how to use HttpClient:
var client = new HttpClient();
var response = client.GetAsync(uriOfYourService).Result;
var content = response.Content.ReadAsAsync<ImportResultDTO>().Result;
(I'm calling .Result() here for the sake of simplicity...)
For more sample of HttpClient, please check this out: List of ASP.NET Web API and HttpClient Samples.
Felipe Oriani
Software Developer since 2004 with focus on back-end development. You can see more about my professional careear at Stack Overflow Careers Profile or LinkedIn profile.
Updated on October 18, 2020Comments
-
Felipe Oriani over 3 years
I have an application written in Windows Service and this app need to make a call to a WebAPI written in Asp.Net MVC 4 WebAPi. this method in WebAPI return a DTO with primitive type, something like:
class ImportResultDTO { public bool Success { get; set; } public string[] Messages { get; set; } }
and in my webapi
public ImportResultDTO Get(int clientId) { // process.. and create the dto result. return dto; }
My question is, how can I call the webApi from the Windows Service? I have my URL and value of parameter, but I don't know how to call and how to deserialize the xml result to the DTO.
Thank you
-
Felipe Oriani over 11 yearsThank you blins, is there any way to check if the URL of my WebAPI is availible before I call
client.GetAsync(...).Result
? I mean it because the internet connection or my webapi could be unstable and I need to check it before to do a correct eventLog for it. Thank you. -
Felipe Oriani over 11 yearsThank you Maggie. I vote up your awser. Is there any way to check if the URL of my WebAPI is availible before I call client.GetAsync(...).Result ? I mean it because the internet connection or my webapi could be unstable and I need to check it before to do a correct eventLog for it. Thank you.
-
blins over 11 yearsCould you not just wrap the call to GetAysnc in a try/catch block and handle the possible Exception? Try it and follow the stack trace, the inner exceptions look like what you are after (e.g. "No connection could be made because...")