2017-06-29 50 views
0

我一直在使用我的WinForm應用程序的ASP API。這是工作正常,但後來我開始使用命名空間的播放,並開始寫HttpClient Accept頭不起作用

沒有MediaTypeFormatter可從與媒體類型「text/html的」內容閱讀型「產品」 的對象。

我已經創建了新的解決方案,複製了所有的代碼,但它仍然沒有工作。響應格式是text/html,但具有相同標頭(Accept application/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); 
     } 
+0

您的應用程序*接受* json並不意味着服務器將*返回* json。問題出在API中,而不是你發佈的代碼 –

回答

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

編輯:這是您的API端點使用上面的RestService類的測試。它正在爲我工​​作,我從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); 
     } 
    } 
} 
+0

謝謝,但它返回,我得到解析值時遇到的意外字符:<。路徑'',第0行,位置0。 –

+0

聽起來像它沒有從該API返回有效的JSON。 – Arman

+0

那麼,它默認使用XML,但使用Accept標頭,它返回JSON。我已經嘗試過cron和瀏覽器,兩者都很好。唯一的問題是與c#app- –