如何从我们的控制台应用程序调用WebAPI方法?

时间:2016-12-02 06:05:36

标签: rest asp.net-web-api console console-application

我需要从控制台应用程序调用webapi。我写过了 以下代码,但它不起作用:

private static async Task UploadDataFromWebApi() {
    try {
        System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
        client.BaseAddress = new Uri("http://localhost:8077/api/");
        client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
        var resp2 =await  client.GetAsync("Report/GetReportGroup");
        resp2.EnsureSuccessStatusCode();
        var aaa = resp2.Content;
        string result = await aaa.ReadAsStringAsync();
        Console.WriteLine(result);
        Console.ReadLine();
    }    
    catch(Exception ex) {
    }
}        

但如果我调用相同的网址:     来自Rest客户端的http://localhost:8077/api/Report/GetReportGroup 然后它工作正常。

那么如何从我的控制台应用程序中调用web api方法呢?

提前致谢。

1 个答案:

答案 0 :(得分:1)

以下代码适用于我: -

Console.WriteLine("Making API Call...");
using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))
{
client.BaseAddress = new Uri("http://localhost:8077/api/");
HttpResponseMessage response = client.GetAsync("Report/GetReportGroup").Result;
response.EnsureSuccessStatusCode();
  string result = response.Content.ReadAsStringAsync().Result;
Console.WriteLine("Result: " + result);
}
Console.ReadLine();