Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to configure in Minimal API #131

Open
AhmedMa3rouf opened this issue Nov 25, 2021 · 1 comment
Open

How to configure in Minimal API #131

AhmedMa3rouf opened this issue Nov 25, 2021 · 1 comment

Comments

@AhmedMa3rouf
Copy link

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
Copy link
Contributor

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); 
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants