Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC4 Web API - Return OData formatted Json from query without custom MediaTypeFormatter

I am trying to use the new WebAPI beta to build a web service that I can query using the OData query string conventions and have it return OData formatted Json. I also want to use OData 2.0 (instead of 1.0).

While it doesn't look like it has support for the $select option and headers seem to be able to override the $format option, returning an IQueryable generic seems to provide support for most other query options that I need.

What I am really struggling with is how best to provide Json objects that meet the OData 2.0 specification. WebAPI just returns normal Json data when queried. For example, if I perform a GET request of something like this...

http://localhost:XXXXX/vendor/?$filter=RONUMBER eq '2597385'&$select=VENDORID,VENDORNAME&$top=1&$format=Json

..to get the top hit matching the specified RONumber on my dev machine, I get a response containing the following Json...

[{"MEPartNumber":"11-2222-3-4444","MFGPartNumber":"123456-123","MFGSerialNumber":"ABC123","RONumber":"987654321","VendorId":"1234567","VendorName":"ACME SERVICE CENTER"}]

I need Json that meets the OData 2.0 spec. Something more like this..

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"
    }
  }
}

I suppose I could write a custom MediaTypeFormatter to get the structure that I want. I might also be able to modify my returned objects to mimic the structure of the desired Json. Aside from these two options, does anyone know of a clever way to make WebAPI give me OData 2.0 formatted Json objects?

like image 908
racingcow Avatar asked Feb 22 '12 05:02

racingcow


People also ask

How do I get ASP Net Web API to return JSON instead of XML?

By removing application/xml you remove the ability for the Web API to return XML if the client requests that specifically. e.g. if you send "Accept: application/xml" you will still receive JSON.


1 Answers

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.

like image 98
marcind Avatar answered Sep 20 '22 13:09

marcind