2017-06-29 12 views
0

私はWinFormアプリケーションからASP APIを使って作業しています。それは罰金働いていたが、その後、私は名前空間で遊んで開始していると、それはありませんMediaTypeFormatterは、メディアタイプ「text/htmlの」との内容からタイプ「Product」に のオブジェクトを読み取ることが可能ですHttpClient Acceptヘッダーが機能しない

書き始めました。

私は新しいソリューションを作成し、すべてのコードをコピーしましたが、まだ動作していません。応答フォーマットは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

Nugetパッケージを追加するためにアプリケーション*は* JSONがサーバー意志*リターン*のJSONを意味するものではありません受け入れていたことに注意してください。 APIに問題があります。投稿したコードではありません。 –

答えて

0

を製品をGETingための私の方法です:

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

EDIT:上記のRestServiceクラスを使用したAPIエンドポイントのテストです。それは私のために働いています、私はJSONデータをAPIから取得します。私は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- –

関連する問題