When we want to serialize an object to a JSON string in ASP.NET Core's pipeline, we need to work with HttpContext.Response.Body.WriteAsync, unless I'm missing something, as there's no Result property which we can easily use to assign a JsonResult object to.
Unless there's a better alternative, how exactly is serialization achieved by using the above method?
Note: The options for the JSON serializer should be the same as the (default) ones being used in ASP.NET Core 3.1.
If desired (not in our case), they can be modified via the IServiceCollection.AddJsonOptions middleware.
Example:
app.Use( next =>
{
return async context =>
{
if (<someFunkyConditionalExample>)
{
// serialize a JSON object as the response's content, returned to the end-user.
// this should use ASP.NET Core 3.1's defaults for JSON Serialization.
}
else
{
await next(context);
}
};
});