【发布时间】: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