The project introduces a method that processes JTokens in order to return only the properties requested by the client.
- Usage
{
"TrackId": 1,
"AlbumId": 1,
"Bytes": 11170334,
"Composer": "Angus Young, Malcolm Young, Brian Johnson",
"GenreId": 1,
"MediaTypeId": 1,
"Milliseconds": 343719,
"Name": "For Those About To Rock (We Salute You)",
"UnitPrice": 0.99
}
You can request only specific properties of that resource by making the request /api/tracks/1?props=bytes,milliseconds,name
{
"Bytes": 11170334,
"Milliseconds": 343719,
"Name": "For Those About To Rock (We Salute You)"
}
The algorithm supports nested navigation properties as well. If /api/albums/1 returns..
{
"AlbumId": 1,
"ArtistName": "AC/DC",
"Title": "For Those About To Rock We Salute You",
"Track": [
{
"TrackId": 1,
"AlbumId": 1,
"Bytes": 11170334,
"Composer": "Angus Young, Malcolm Young, Brian Johnson",
"GenreId": 1,
"MediaTypeId": 1,
"Milliseconds": 343719,
"Name": "For Those About To Rock (We Salute You)",
"UnitPrice": 0.99
},
{
"TrackId": 6,
"AlbumId": 1,
"Bytes": 6713451,
"Composer": "Angus Young, Malcolm Young, Brian Johnson",
"GenreId": 1,
"MediaTypeId": 1,
"Milliseconds": 205662,
"Name": "Put The Finger On You",
"UnitPrice": 0.99
}
]
}
Then /api/albums/1?props=artistname,title,track(composer;name) should return the following:
{
"ArtistName": "AC/DC",
"Title": "For Those About To Rock We Salute You",
"Track": [
{
"Composer": "Angus Young, Malcolm Young, Brian Johnson",
"Name": "For Those About To Rock (We Salute You)"
},
{
"Composer": "Angus Young, Malcolm Young, Brian Johnson",
"Name": "Put The Finger On You"
}
]
}
Properties in navigations should be semicolon (;) separated inside parethensis.
- Example in API Controller
var _tracks = _trackRepository.GetAll(includeProperties).Skip(page).Take(pageSize);
var _tracksVM = Mapper.Map<IEnumerable<Track>, IEnumerable<TrackViewModel>>(_tracks);
string _serializedTracks = JsonConvert.SerializeObject(_tracksVM, Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
JToken _jtoken = JToken.Parse(_serializedTracks);
if (!string.IsNullOrEmpty(props))
Utils.FilterProperties(_jtoken, props.ToLower().Split(',').ToList());
return Ok(_jtoken);
The project is built in Visual Studio 2015 and ASP.NET Core but the technique and the method can be easily integrated in any version of ASP.NET API. In case you want to run the ShapingAPI application:
- Download the source code and open the solution in Visual Studio 2015
- Restore Nuget and Bower packages
- Install the Chinook database in your SQL Server by running the script inside the SQL folder.
- Alter the appsettings.json file to reflect your database environment.
- Run the application
If you think that any information you obtained here is worth of some money and are willing to pay for it, feel free to send any amount through paypal.
Paypal |
---|
Microsoft Web Application Development | |||