Open abhalesd opened 2 years ago
did you ever work this out?
JsonApiSerializer only focuses on the serialization and de-serialization of JSON:API responses.
Pagination, Filtering, Sorting... are not part of this library and have to be implemented yourself.
The biggest challenge is parsing the query parameters manually because ASP.NET Core's Model Binding does not understand the format that the JSON:API specification uses.
For example filtering multiple values (filter[id]=1,2,3,4) would require getting the parameter from the query manually, and then splitting the value by comma.
A minimal example using ASP.NET Core, Minimal APIs and EntityFramework Core would be:
// endpoint to get all media items
app.MapGet("/v1/media-items", async (HttpContext ctx, AppDbContext db) =>
{
var query = ctx.Request.Query;
// filter by ids
if( query["filter[id]"].Count() > 0 ) {
// split the values by comma
var ids = query["filter[id]"].Split(',', StringSplitOptions.RemoveEmptyEntries)
// convert the strings to numbers
.Select(id => Int32.TryParse(idStr, out var idInt) ? idInt : null)
// remove null values caused by failed conversions
.Where(id => id != null)
// convert to a list for easier handling
.ToList();
if ( ids.Count > 0 ) {
// get the filtered items from the database
var mediaItems = await db.MediaItems.Where(mi => ids.Contains(mi.Id)).ToListAsync();
// serialize a response and return a ContentResult with the correct custom Content-Type
var json = JsonConvert.SerializeObject(mediaItems, new JsonApiSerializerSettings());
return Results.Content(json, "application/vnd.api+json", Encoding.UTF8);
}
var allMediaItems = await db.MediaItems.ToListAsync();
var allJson = JsonConvert.SerializeObject(allMediaItems, new JsonApiSerializerSettings());
return Results.Content(allJson, "application/vnd.api+json", Encoding.UTF8);
}
});
If you want to go easy mode, there is another project called JsonApiDotnetCore (jsonapi.net) that autogenerates a JSON:API that supports everything you asked for out of the box, but beware of a lot of bloated magic. IMHO, it's only suitable for larger projects with multiple entities but overkill for simple microservices that only have 1-2 entities and have to be really fast.
Hello, I am completely new to json api serializer. I am looking for it, so that I can implement pagination, sorting easily. Do you have any sample project implemented with this functionality in .net core? Or can you point me to documentation about how it can be implemented?