2016-09-05 5 views
1

jsonを返すwebservicesを作成したいと思います。しかし、私は常にレスポンスのコンテンツタイプとして「text/html」を取得しています。asp.net webAPIがいつもtext/htmlを返すのはなぜですか?

最初のショット:

public StringContent Get() 
{ 
    List<Cell> list = new List<Cell>(); 
    Cell c = new Cell("Cell1"); 
    Cell c2 = new Cell("Cell2"); 
    list.Add(c); 
    list.Add(c2); 

    return new StringContent(
     Newtonsoft.Json.JsonConvert.SerializeObject(list), 
     Encoding.UTF8, 
     "application/json"); 
} 

Responsecontent:System.Net.Http.StringContent

セカンドショット:

public List<Cell> Get() 
    { 
     Cell c = new Models.Cell("Cell1"); 
     List<Cell> list = new List<Cell>(); 
     list.Add(c); 
     return list; 
    } 

Responsecontent:System.Collections.Generic.List`1【でTestApp .Models.Cell]

これは私がエンドポイントにアクセスする方法である:

$.ajax({ 
      url: "http://localhost:54787/Cell/Get", 
      type: "GET", 
      contentType:"application/json", 
      accepts: { 
       text: "application/json" 
      },  
      success: function (response) { 
       $("#result").html(JSON.parse(response)); 
      }, 
      error: function (xhr, status) { 
       alert("error"); 
      } 
     }); 

enter image description here

+0

エンドポイントをどのようにテストしていますか? – zulq

+0

私は '/ Cell/Get'をchromeから呼び出しています。私もjQuery $ .ajax get Requestを試して、chromeのネットワークモニタをチェックしました。 – user66875

+1

あなたはこれを見ましたか? http://stackoverflow.com/questions/9847564/how-do-i-get-asp-net-web-api-to-return-json-instead-of-xml-using-chrome?rq=1 – zulq

答えて

1

手動でシリアライズを行うには十分な理由がない場合は、代わりにStringContentのオブジェクトを返すことによって、Web APIのデフォルト・メカニズムを使用する必要があります。たとえば、List<Cell>を直接返すようにメソッドを変更できます。

public List<Cell> Get() 
{ 
    // return List<Cell> just like you write a typical method 
} 

この方法では、text/htmlはもう取得できません。しかし、あなたはまだChromeでXMLを取得します。 ChromeのデフォルトのHTTP Acceptヘッダーにはapplication/xmlが含まれており、Web APIではデフォルトでサポートされているためです。あなたがXML結果をサポートする必要がないので、あなたは(多分Global.asaxの中で)起動時に以下のコードでそれを削除することができた場合は

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 

PS:あなたがXMLを必要とするかどうかわからない場合は、あなたはそれを必要としません。

+0

ありがとうございます。投稿を更新してコードの結果を追加しました。私は本当に 'text/html'をなぜ返すのか理解できません。 – user66875

関連する問題