【问题标题】:HttpClient - body content is not returned?HttpClient - 不返回正文内容?
【发布时间】:2019-06-04 03:45:31
【问题描述】:

响应始终为空,但通过 curl 进行 api 调用时会返回正文内容。

        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://localhost:5008/Accounts/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "ACCESSTOKENHERE");

            //GET Method  
            HttpResponseMessage httpResponse = await client.GetAsync("searchKeyword=" + searchKeyword);

            try
            {
                AccountListResponse response = await httpResponse.Content.ReadAsAsync<AccountListResponse>();
            }
            catch (Exception)
            {
            }

        }

【问题讨论】:

  • 你确定 curl 发送的 headers 和你发送的 headers 是一样的吗?我最近在这里回答了一个类似的问题(在浏览器中工作,而不是在代码中工作),结果发现客户端根本没有发送用户代理标头,服务器什么也没发回
  • 我假设你已经缩短了这段代码..来自服务器的响应数据实际上可以转换为帐户列表响应吗?还是它发送了一些东西,但返回 null 的是您的转换尝试? ReadAsStringAsync 给你什么?
  • @CaiusJard ReadAsStringAsync 返回一个空字符串。
  • 使用curl调用web api,可以。在代码中,尝试调用同一个web api,错误401 Unauthorized
  • 已修复,我缺少一个“?”在查询参数中! ("searchKeyword=" ...假设是 ("?searchKeyword=" ...我忽略了...直到现在才看到 ? 问号丢失:)

标签: c# asp.net api asp.net-core httpclient


【解决方案1】:

我只能为您提供疑难解答帮助,因为您的问题不包含来自您的 api 调用的示例响应。

为了解决问题, 将响应读取为字符串。然后检查您是否收到回复。以及 statusCode。

.Content.ReadAsStringAsync()

如果这给出了结果。那么您的 AccountListResponse 没有正确的响应映射。

使用 json to c# 方法生成正确的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 2018-06-14
    • 1970-01-01
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多