11

我有一个用 Windows 服务编写的应用程序,这个应用程序需要调用一个用 Asp.Net MVC 4 WebAPi 编写的 WebAPI。WebAPI 中的此方法返回原始类型的 DTO,例如:

class ImportResultDTO {
   public bool Success { get; set; }
   public string[] Messages { get; set; }
}

在我的 webapi 中

public ImportResultDTO Get(int clientId) {
   // process.. and create the dto result.
   return dto;
}

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

谢谢

4

2 回答 2

19

您可以使用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);
}
于 2012-10-17T21:25:15.923 回答
4

您可以将此 NuGet 包Microsoft ASP.NET Web API 客户端库安装到您的 Windows 服务项目。

下面是一个简单的代码片段,演示了如何使用 HttpClient:

        var client = new HttpClient();
        var response = client.GetAsync(uriOfYourService).Result;
        var content = response.Content.ReadAsAsync<ImportResultDTO>().Result;

(为了简单起见,我在这里调用 .Result() ......)

有关 HttpClient 的更多示例,请查看: ASP.NET Web API 和 HttpClient 示例列表。

于 2012-10-17T21:28:33.963 回答