简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM