HttpClient Accept标头不起作用

时间:2017-06-29 18:05:33

标签: c# asp.net rest api client

我一直在使用WinForm应用程序中的ASP API。它工作正常,但后来我开始使用命名空间,它开始编写

  

没有MediaTypeFormatter可用于读取'产品'   来自媒体类型的内容' text / html'。

我创建了新的解决方案,复制了所有代码,但它仍然无效。响应格式是text / html,尽管具有相同标题的curl命令(Accept application / json)工作正常。

这是我从API获取产品的方法

root 'project#index'

1 个答案:

答案 0 :(得分:0)

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

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);
        }
    }
}