Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using new Json serializer with HttpContext.Response in ASP.NET Core 3.1

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);
        }
    };
});
like image 891
SpiritBob Avatar asked Mar 16 '20 14:03

SpiritBob


Video Answer


1 Answers

First of all, you can use these extension methods to write strings directly to your response, for example:

await context.Response.WriteAsync("some text");

Make sure you have imported the correct namespace to give you access to these extensions:

using Microsoft.AspNetCore.Http;

Secondly, if you want to get the JSON serialiser settings that are being used by the framework, you can extract them from the DI container:

var jsonOptions = context.RequestServices.GetService<IOptions<JsonOptions>>();

So this would make your full pipeline code look a little like this:

app.Use(next =>
{
    return async context =>
    {
        if (<someFunkyConditionalExample>)
        {
            // Get the options
            var jsonOptions = context.RequestServices.GetService<IOptions<JsonOptions>>();

            // Serialise using the settings provided
            var json = JsonSerializer.Serialize(
                new {Foo = "bar"}, // Switch this with your object
                jsonOptions?.Value.JsonSerializerOptions);

            // Write to the response
            await context.Response.WriteAsync(json);
        }
        else
        {
            await next(context);
        }
    };
});
like image 55
DavidG Avatar answered Sep 28 '22 04:09

DavidG