JSONserializersettings and ASP.NET Core

How to set json serializer settings in asp.net core 3?

AddMvc returns an IMvcBuilder implementation, which has a corresponding AddJsonOptions extension method. The new-style methods AddControllers, AddControllersWithViews, and AddRazorPages also return an IMvcBuilder implementation. Chain with these in the same way you would chain with AddMvc:

services.AddControllers()
.AddJsonOptions(options =>
{
// ...
});

Note that options here is no longer for Json.NET, but for the newer System.Text.Json APIs. If you still want to use Json.NET, see tymtam's answer

asp .net core 6 how to update option for json serialization. Date format in Json serialization

We can try to use builder.Services.Configure<JsonOptions> to set our Serializer setting in DI container from .net core 6

JsonOptions let us configure JSON serialization settings, which might instead AddJsonOptions method.

JsonOptionsmight use same as JsonOptions object from DI in the SourceCode.

using Microsoft.AspNetCore.Http.Json;

builder.Services.Configure<JsonOptions>(options =>
{
options.SerializerOptions.Converters.Add(new DateTimeConverterForCustomStandardFormatR());
});

I think this change is based on Microsoft wanting to introduce minimal web API with ASP.NET Core in .net 6

Minimal APIs are architected to create HTTP APIs with minimal dependencies. They are ideal for microservices and apps that want to include only the minimum files, features, and dependencies in ASP.NET Core.

How to get current JsonSerializerOptions in ASP.NET Core 3.1?

You could inject IOptions<JsonOptions> or IOptionsSnapshot<JsonOptions> as per Options pattern into your middleware.

public async Task Invoke(HttpContext httpContext, IOptions<JsonOptions> options)
{
JsonSerializerOptions serializerOptions = options.Value.JsonSerializerOptions;

await _next(httpContext);
}

AspNet Core - input/output JSON serialization settings at Controller Level

The answer you link works well enough, but you can extend it further by wrapping it in an attribute that you can apply to any action or controller. For example:

public class JsonConfigFilterAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
if (context.Result is ObjectResult objectResult)
{
var serializerSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver()
};

var jsonFormatter = new JsonOutputFormatter(
serializerSettings,
ArrayPool<char>.Shared);

objectResult.Formatters.Add(jsonFormatter);
}

base.OnResultExecuting(context);
}
}

And just add it to action methods or controllers:

[JsonConfigFilter]
public ActionResult<Foo> SomeAction()
{
return new Foo
{
Bar = "hello"
};
}


Related Topics



Leave a reply



Submit