如何调用从Windows服务的WebAPIWindows、WebAPI

由网友(失忆三叶草)分享简介:我写的Windows服务的应用程序,这个程序需要打电话到写在Asp.Net MVC 4的WebAPI一个的WebAPI。这种方法的WebAPI返回一个DTO与原始类型,是这样的:I have an application written in Windows Service and this app need to...

我写的Windows服务的应用程序,这个程序需要打电话到写在Asp.Net MVC 4的WebAPI一个的WebAPI。这种方法的WebAPI返回一个DTO与原始类型,是这样的:

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; }
}

和我的WebAPI

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

我的问题是,我怎么能叫从Windows服务中的WebAPI?我有我的URL和参数的值,但我不知道该怎么称呼,如何反序列化的XML结果的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.

感谢您

推荐答案

您可以使用System.Net.Http.HttpClient.你会明显需要修改的假基地址和请求的URI在下面的例子,但是这也说明一个基本的方法来检查响应状态也是如此。

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);
}
阅读全文

相关推荐

最新文章