2016-04-08 2 views
1

私はコードWebAPIのMVC 4セットのデフォルトの応答タイプ

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 
config.Formatters.JsonFormatter.MediaTypeMappings.Add(
    new UriPathExtensionMapping("json", "application/json")); 
config.Formatters.XmlFormatter.MediaTypeMappings.Add(
    new UriPathExtensionMapping("xml", "application/xml")); 

を以下している今、私はいくつかのいずれかがhttp://apuUrl/getBooksのようなAPIの拡張機能を提供しない場合、それはデフォルトJSON値で返す必要がありますしたいです。

私の次のシナリオが正常に動作している:私はすべてのAPI

+0

可能な複製:http://stackoverflow.com/questions/13053485/return-either-xml-or-json-from-mvc-web-api-based-on-request – smoksnes

+0

これを見ました...しかし、これはすべてのAPIに追加のルーティングが必要です –

+0

コンテンツタイプを設定することで達成できます。それは選択肢ですか、それともルートにある必要がありますか? – smoksnes

答えて

2
のための余分なルーティングをしたくない:

http://apuUrl/getBooks.json - > XML

注意を返す - >は、JSON

http://apuUrl/getBooks.xmlを返します

DelegatingHandlerを使用してacceptheaderを無効にすることはどうですか?

public class MediaTypeDelegatingHandler : DelegatingHandler 
{ 
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 
    { 
     var url = request.RequestUri.ToString(); 
     //TODO: Maybe a more elegant check? 
     if (url.EndsWith(".json")) 
     { 
      // clear the accept and replace it to use JSON. 
      request.Headers.Accept.Clear(); 
      request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
     } 
     else if (url.EndsWith(".xml")) 
     { 
      request.Headers.Accept.Clear(); 
      request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); 
     } 
     return await base.SendAsync(request, cancellationToken); 
    } 
} 

そして、あなたの設定で:

GlobalConfiguration.Configuration.MessageHandlers.Add(new MediaTypeDelegatingHandler()); 

そして、あなたのコントローラ:

public class FooController : ApiController 
{ 
    public string Get() 
    { 
     return "test"; 
    } 
} 

そして、あなたはhttp://yoursite.com/api/Foo/?.jsonに行けば返す必要があります:

"test" 

ながらコントローラは.jsonパラメータを期待していないので、あなたはまだ、ルートパラメータの入力を処理する必要が 注:は

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">test</string> 

編集を返す必要があります。そのため、?が必要な場合があります。