我在从HttpClient PostAsJsonAsync方法获取响应时遇到问题。我正在将StringContent数据传递给POST请求,但它返回了禁止的(403)状态代码。
当我尝试添加默认请求标头(代码的注释行)时,该错误发生了更改,并返回了超时问题:
{System.Net.Http.WinHttpException(0x80072EE2):操作超时 在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在System.Threading.Tasks.RendezvousAwaitable`1.GetResult() 在System.Net.Http.WinHttpHandler.d__105.MoveNext()}
var content = new StringContent(JsonConvert.SerializeObject(contentBody), Encoding.UTF8, "application/json");
var client = new HttpClient();
client.BaseAddress = new Uri("https://www.example.com");
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
using (var httpResponse = await client.PostAsJsonAsync("api/details", content))
{
if (httpResponse.Content != null)
{
var responseContent = await httpResponse.Content.ReadAsStringAsync();
}
}
当我在Postman中尝试时,它返回了JSON数据。为什么它在代码中不起作用?有什么阻碍我的联系的吗?
答案 0 :(得分:2)
BaseAddress
属性必须以正斜杠后缀:
client.BaseAddress = new Uri("https://www.example.com/");