のための余分なルーティングをしたくない:
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>
編集を返す必要があります。そのため、?
が必要な場合があります。
可能な複製:http://stackoverflow.com/questions/13053485/return-either-xml-or-json-from-mvc-web-api-based-on-request – smoksnes
これを見ました...しかし、これはすべてのAPIに追加のルーティングが必要です –
コンテンツタイプを設定することで達成できます。それは選択肢ですか、それともルートにある必要がありますか? – smoksnes