【问题标题】:HttpClient Accept header doesn't workHttpClient Accept 标头不起作用
【发布时间】: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


【解决方案1】:

在阅读内容之前为您的回复设置此项:

response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

旁注:顺便说一句,我在很多个月前创建了这个,以避免在应用程序的不同区域不必要地杀死和重新实例化 HttpClient。它从来没有让我失望,它使我的应用程序中的任何休息服务清洁器都可以进行通信。这让我更灵活地决定何时结束 HttpClient 连接并动态控制从结果中解析的对象类型。希望对你也有帮助。

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Foo
{
    public class RestService : IDisposable
    {
        private bool _disposed = false;
        private HttpClient _client;

        public RestService()
        {
            _client = new HttpClient();
            _client.Timeout = TimeSpan.FromSeconds(60);
        }

        public async Task<T> GetRequest<T>(string queryURL)
        {
            T result = default(T);
            using (HttpResponseMessage response = _client.GetAsync(queryURL).Result)
            {
                if (response.IsSuccessStatusCode)
                {
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    using (HttpContent content = response.Content)
                    {
                        result = await content.ReadAsAsync<T>();
                    }
                }
                else
                {
                    throw new HttpRequestException(response.ReasonPhrase);
                }
            }

            return result;
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_client != null)
                    {
                        _client.Dispose();
                    }
                }

                _disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

编辑:这是使用上面的 RestService 类对您的 API 端点进行的测试。它对我有用,我从 API 获取 JSON 数据。注意我必须添加 Nuget 包 Microsoft.AspNet.WebApi.Client

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace SOTest
{
    public class Program
    {
        public static void Main(string[] args)
        {

            using (RestService rs = new RestService())
            {
                var result = rs.GetRequest<Product>(@"http://eshop.sambacentrum.tumam.cz/api/byznys/GetProduct?code=sup100").Result;
                Console.WriteLine(result.Name);
            }

            Console.ReadKey();
        }

    }

    public class Product
    {
        public string Amount { get; set; }
        public string Code { get; set; }
        public string CodeEAN { get; set; }
        public string Name { get; set; }
        public string Price { get; set; }
        public string PriceWithTax { get; set; }
        public string Text { get; set; }
    }

    public class RestService : IDisposable
    {
        private bool _disposed = false;
        private HttpClient _client;

        public RestService()
        {
            _client = new HttpClient();
            _client.Timeout = TimeSpan.FromSeconds(60);
        }

        public async Task<T> GetRequest<T>(string queryURL)
        {
            T result = default(T);
            using (HttpResponseMessage response = _client.GetAsync(queryURL).Result)
            {
                if (response.IsSuccessStatusCode)
                {
                    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                    using (HttpContent content = response.Content)
                    {
                        result = await content.ReadAsAsync<T>();
                    }
                }
                else
                {
                    throw new HttpRequestException(response.ReasonPhrase);
                }
            }

            return result;
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    if (_client != null)
                    {
                        _client.Dispose();
                    }
                }

                _disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}

【讨论】:

  • 谢谢,但它返回 并且我在解析值时遇到意外字符:
  • 听起来它没有从该 API 返回有效的 JSON。
  • 嗯,它默认使用 XML,但使用 Accept 标头,它返回 JSON。我已经尝试过 cron 和浏览器,它们都工作得很好。唯一的问题是 c# 应用程序-
  • link 这是从 api 获取的请求
  • 我无法重现该问题。尝试使用我上面的 RestService 类。我正在使用它,它以 JSON 格式返回您的数据集就好了。你的Product 班级是什么样的?
猜你喜欢
  • 2012-06-18
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-30
  • 2011-12-21
相关资源
最近更新 更多