Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve json serializer settings via DI (service collection) in asp netcore 3.1 mvc while using AddNewtonsoftJson

I have an ASP MVC project using .netcore 3.1, where I am overriding serializer options as the following

services
.AddControllers()
.AddNewtonsoftJson(options =>
{
    options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
    options.SerializerSettings.NullValueHandling = NullValueHandling.Include;
    options.SerializerSettings.Converters.Add(new StringEnumConverter
    {
        NamingStrategy = new CamelCaseNamingStrategy(),
    });
})

This works fine whenever MVC is serialising data (request/response) for me. But now, in one of the Middlewares I need to serialise manually and return some data as a response, like:

public async Task Invoke(HttpContext context)
{
    try
    {
        await _next(context);
    }
    catch (Exception exception)
    {
        ... // removed for simplicity
        await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse, _jsonSerializerSettings));
    }
}

Here I want to reuse existing settings for serialization. But old MvcJsonOptions are not available in .netcore 3.1 anymore (please correct if I am wrong). So how can I achieve this, without duplicating json serialization settings?

like image 919
shaderzak Avatar asked Feb 11 '20 12:02

shaderzak


People also ask

How to use JSON serializer in ASP NET Core?

You can using JSON serializer in ASP.NET Core (Using .NET 5), by adding Nuget package first Install-Package Microsoft.AspNetCore.Mvc.NewtonsoftJson or, if you want to add Custom Serializer, you can add this code, in above configuration // Configure a custom converter options.SerializerOptions.Converters.Add ( new YourCustomJsonConverter ());

How to use default serialization in ASP NET Core?

The recommended approach is to use the default serialization that is delivered with ASP.NET Core. To configure it, locate the ConfigureServices method and update it by adding the code below. The first alternative approach is to maintain the property names casing globally.

What is the default serialization for the jsonproperty?

It will be serialized like : So you’ll notice that the first property has the first letter capitalized (essentially PascalCase), but the second property without the JsonProperty attribute is using the default .NET Core serialization which is camelCase. This may seem OK, but what if you then change the default serialization for .NET Core?

How do I return a jsonserializer result?

There are two ways to do that: return JsonResult and pass it a JsonSerializerOptions object, or by directly using JsonSerializer. I’ll show both approaches below.


1 Answers

Here I want to reuse existing settings for serialization.

Since you've configured the NewtonsoftJson Options For Mvc within ConfigureServices() method, just inject a IOptions<MvcNewtonsoftJsonOptions> when you need it. For example, change your middleware to accept an argument of IOptions<MvcNewtonsoftJsonOptions>:

public class MyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly JsonSerializerSettings _jsonSerializerSettings;

    public MyMiddleware(RequestDelegate next,IOptions<MvcNewtonsoftJsonOptions> jsonOptions)
    {
        // ... check null and throw
        this._next = next;
        this._jsonSerializerSettings = jsonOptions.Value.SerializerSettings;
    }

    public async Task Invoke(HttpContext context) 
    {
        try
        {
            await _next(context);
        }
        catch (Exception exception)
        {
            //... removed for simplicity
            await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResponse, _jsonSerializerSettings));
        }
    }
}
like image 117
itminus Avatar answered Oct 18 '22 23:10

itminus