C# 如何从 Windows 服务调用 WebAPI
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12942644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a WebAPI from Windows Service
提问by Felipe Oriani
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:
我有一个用 Windows 服务编写的应用程序,这个应用程序需要调用一个用 Asp.Net MVC 4 WebAPi 编写的 WebAPI。WebAPI 中的此方法返回具有原始类型的 DTO,例如:
class ImportResultDTO {
public bool Success { get; set; }
public string[] Messages { get; set; }
}
and in my webapi
在我的 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.
我的问题是,如何从 Windows 服务调用 webApi?我有我的 URL 和参数值,但我不知道如何调用以及如何将 xml 结果反序列化到 DTO。
Thank you
谢谢
采纳答案by blins
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.
您可以使用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);
}
回答by Maggie Ying
You can install this NuGet package Microsoft ASP.NET Web API Client Librariesto your Windows Service project.
您可以将此 NuGet 包Microsoft ASP.NET Web API 客户端库安装到您的 Windows 服务项目中。
Here is a simple code snippet demonstrating how to use HttpClient:
这是一个简单的代码片段,演示了如何使用 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...)
(为了简单起见,我在这里调用 .Result() ......)
For more sample of HttpClient, please check this out: List of ASP.NET Web API and HttpClient Samples.
有关 HttpClient 的更多示例,请查看: ASP.NET Web API 和 HttpClient 示例列表。

