【问题标题】:Why can my WebApi client make only a single GET request?为什么我的 WebApi 客户端只能发出一个 GET 请求?
【发布时间】:2014-07-23 18:52:47
【问题描述】:

按照本教程中的说明,我使用 Web Api 为我的 Web 服务编写了一个简单的客户端:

http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

第一个请求(GET a table)成功执行。也就是说,表格数据是从 Web 服务中获取并绑定到 TableContent 对象的。

但是程序在执行第二个请求(GET表列表)之前就被完全阻塞了;什么都没有发生,甚至没有错误消息!

如果我注释掉与第一个请求(GET a table)相关的代码部分,则第二个请求(GET table list)执行成功。

这里发生了什么?为什么这个客户端只能执行一个 GET 请求?

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:56510/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response;

    // GET a table from web service
    response = await client.GetAsync("api/table/GetMatrixTable");

    if (response.IsSuccessStatusCode)
    {
        var tblcont = await response.Content.ReadAsAsync<TableContent>();
        // do things ...
    }

    // GET a table list from web service
    response = await client.GetAsync("api/table/GetTableList");

    if (response.IsSuccessStatusCode)
    {
        var TblContList = await response.Content.ReadAsAsync<IList<TableContent>>();
        // do things ...
    }
}

【问题讨论】:

  • 听起来像一个僵局,但我不知道究竟是什么原因。这个客户端是什么类型的应用程序?包含您的代码示例的方法是如何调用的?
  • 此客户端是本教程中解释的控制台应用程序 (.NET 4.5):asp.net/web-api/overview/web-api-clients/… 如本教程所示,Main() 中的语句“RunAsync().Wait()”调用“静态异步任务 RunAsync()”,它封装了此处显示的 using{} 块。

标签: c# .net web-services asp.net-web-api datatable


【解决方案1】:

查看以下 SO 问题及其接受的答案(可能不直接相关但本身仍然有用):

如果您将呼叫替换为 GetAsync() 可能会有所帮助:

response = await client.GetAsync("api/table/GetMatrixTable",
                 HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
. . .
response = await client.GetAsync("api/table/GetTableList",
                 HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);

我无法对此进行测试,因此如果它有效,我无法承担所有功劳。

【讨论】:

  • 感谢 djikay,@tuncalik 真的应该将此标记为答案。
猜你喜欢
  • 1970-01-01
  • 2017-09-24
  • 2017-08-07
  • 1970-01-01
  • 2010-11-28
  • 1970-01-01
  • 2016-12-03
  • 1970-01-01
  • 2021-10-14
相关资源
最近更新 更多