如何从Windows服务调用WebAPI

Fel*_*ani 10 .net c# asp.net-mvc windows-services asp.net-web-api

我有一个用Windows Service编写的应用程序,这个应用程序需要调用用Asp.Net MVC 4 WebAPi编写的WebAPI.WebAPI中的此方法返回具有基本类型的DTO,如:

class ImportResultDTO {
   public bool Success { get; set; }
   public string[] Messages { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

在我的webapi

public ImportResultDTO Get(int clientId) {
   // process.. and create the dto result.
   return dto;
}
Run Code Online (Sandbox Code Playgroud)

我的问题是,如何从Windows服务中调用webApi?我有我的URL和参数值,但我不知道如何调用以及如何将xml结果反序列化到DTO.

谢谢

bli*_*ins 18

您可以使用System.Net.Http.HttpClient.显然,您需要在下面的示例中编辑伪基址和请求URI,但这也显示了检查响应状态的基本方法.

// 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);
}
Run Code Online (Sandbox Code Playgroud)