如何调用从Windows服务的WebAPI [英] How to call a WebAPI from Windows Service

查看:709
本文介绍了如何调用从Windows服务的WebAPI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的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.

感谢您

推荐答案

您可以使用<一个href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx">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);
}

这篇关于如何调用从Windows服务的WebAPI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆