codecutout / JsonApiSerializer

JsonApiSerializer supports configurationless serializing and deserializing objects into the json:api format (http://jsonapi.org).
MIT License
113 stars 47 forks source link

How to configure in Minimal API #131

Open AhmedMa3rouf opened 2 years ago

AhmedMa3rouf commented 2 years ago

how i can configure .net 6 (Minimal API) to use the JsonApiSerializer as a default Json format?? i can set it in each map but i want to set it as an default format

this is will working app.MapGet("/GetAll", async (AppDBContext db) => JsonConvert.SerializeObject(await db.Banks.ToArrayAsync(), new JsonApiSerializerSettings()));

but the output is a text not json

wavedeck commented 5 months ago

I'm afraid that overriding the json serializer is not possible in minimal apis. (correct me if I'm wrong) This was a design decision by the ASP.NET Core team, to keep minimal apis simple and performant.

So you'd have to use JsonConvert.SerializeObject within all handlers like you already do.

Additionally, SerializeObject returns a string. That's why ASP.NET returns a Content-Type of text/plain.

To make this approach work correctly with minimal apis, you need to return a Results.Content response and set your own Content-Type.

For example:


app.MapGet("/hello-world", async () => {

    // get a list of banks from the database
    var banks = await db.Banks.ToListAsync();

    // serialize to a jsonapi formatted string
    var jsonResponse = JsonConvert.SerializeObject(banks, new JsonApiSerializerSettings());

    // return a ContentResult with an optional http status code
    return Results.Content(jsonResponse, "application/vnd.api+json", 200); 
})
wavedeck commented 5 months ago

To make this approach work correctly with minimal apis, you need to return a Results.Content response and set your own Content-Type.

This is also how i currently use it in ASP.NET Core minimal api's with .NET 8.

Keep in mind, that this library uses an outdated and vulnerable version of Newtonsoft.Json and seems not actively maintained anymore. For that reason, I've refactored and updated this project over on my fork and plan to maintain it for both .NET Framework 4.6.2+ (v1) .NET 6+ (upcoming v2 - but v1 works as well for now).

I appreciate the work done by the original author and would like to keep it alive as a simple way to De-/Serialize JSON:API Responses, especially compared to the much more complex JsonApiDotnetCore (jsonapi.net) project