【发布时间】:2017-07-05 18:39:08
【问题描述】:
我一直在我的 WinForm 应用程序中使用 ASP API。它工作正常,但后来我开始使用命名空间,它开始编写
没有 MediaTypeFormatter 可用于读取“产品”类型的对象 来自媒体类型为“text/html”的内容。
我创建了新的解决方案,复制了所有代码,但仍然无法正常工作。响应格式为 text/html,尽管具有相同标头(接受应用程序/json)的 curl 命令工作正常。
这是我从 API 获取产品的方法
public static async Task<ProductWithBool> GetProductByIdAsync(string id)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://eshop.ApiUpdatercentrum.tumam.cz/api/byznys/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Product product = null;
HttpResponseMessage response = await client.GetAsync("GetProduct?code=" + id);
if (response.IsSuccessStatusCode)
{
product = await response.Content.ReadAsAsync<Product>();
}
else
{
ErrorManager.AddError("Getting product failed");
return new ProductWithBool(null, 2);
}
if (product == null)
{
ErrorManager.AddError("Product not found");
return new ProductWithBool(null, 1);
}
return new ProductWithBool(product, 0);
}
【问题讨论】:
-
您的应用程序接受 json 并不意味着服务器将返回 json。问题出在 API 中,而不是您发布的代码中
标签: c# asp.net rest api client