【问题标题】:How to call WebAPI method from our Console application?如何从我们的控制台应用程序调用 WebAPI 方法?
【发布时间】:2016-12-02 06:05:35
【问题描述】:

我需要从控制台应用程序调用 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) {
    }
}        

但是如果我调用的是相同的 url,那就是: http://localhost:8077/api/Report/GetReportGroup 来自 Rest 客户端 那么它工作正常。

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

提前致谢。

【问题讨论】:

  • 而不是 resp2.EnsureSuccessStatusCode();检查状态码和响应内容

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


【解决方案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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2021-05-20
    相关资源
    最近更新 更多