Asp.Net MVC4 WebAPI-カスタムMediaTypeFormatterなしでクエリからOData形式のJsonを返します
-
29-10-2019 - |
質問
新しい webapi ベータ版を使用しようとしています。 ODATA QUERY STRING Conventions を返し、 OdataフォーマットされたJSON 。また、OData 2.0(1.0の代わりに)を使用したいです。
$ select オプションとヘッダーは $ format オプションをオーバーライドできるようです。 、IQueryable
汎用の宛先を返すと、必要なほとんどのクエリオプションをサポートしています。
私が本当に苦労しているのは、OData 2.0仕様を満たすJSONオブジェクトをどのように提供するのが最善です。 WebAPIは照会されたときに通常のJSONデータを返します。たとえば、このようなものの取得要求を実行した場合は...
http://localhost:XXXXX/vendor/?$filter=RONUMBER eq '2597385'&$select=VENDORID,VENDORNAME&$top=1&$format=Json
.
..先頭のヒットを取得するには、Devマシン上の指定されたつらられたつららを一致させるには、次のJSON ... を含む応答が得られます。
[{"MEPartNumber":"11-2222-3-4444","MFGPartNumber":"123456-123","MFGSerialNumber":"ABC123","RONumber":"987654321","VendorId":"1234567","VendorName":"ACME SERVICE CENTER"}]
.
OData 2.0仕様を満たすJSONが必要です。このような何かこのようなもの。
OData V2: {
"d" : {
"results": {
"__metadata": {
"uri": "http://someserver/foo/vendor(1)",
"type": "Vendor"
},
"MEPartNumber": "11-2222-3-4444",
"MFGPartNumber": "123456-123",
"MFGSerialNumber": "ABC123",
"RONumber":"987654321",
"VendorId":"1234567",
"VendorName": "ACME SERVICE CENTER"
}
}
}
.
私は私が欲しい構造を得るためにカスタムMediaTypeFormatter
を書くことができたと思います。また、私の返品オブジェクトを変更して、目的のJSONの構造を模倣することができます。これら2つの選択肢とは別に、WebAPIを作るための賢い方法を知っていますか?
解決
You need to write your own MediaTypeFormatter
to provide the right serialization. We didn't ship an OData formatter in the MVC 4 Beta, but the previous incarnation of WCF Web Api has some examples of how to write one. http://wcf.codeplex.com/SourceControl/list/changesets Look for Microsoft.Net.Http.Formatting.OData (you should be able to use most of the source, though some implementation details might've changed)
An alternative would be to try to construct a DTO that would serialize to the shape expected by OData v2.