asp .net core 6 如何更新 json 序列化选项。Json序列化中的日期格式

Ser*_*kyi 15 c# json asp.net-core asp.net-core-3.0 asp.net-core-6.0

我对这个愚蠢的问题表示歉意,但我没有看到一个很好的例子来说明如何在 .net core 6 的 JSON 序列化中为 DateTime 指定特定格式。

老办法,net core 3。

// in the ConfigureServices()
services.AddControllers()
    .AddJsonOptions(options =>
     {
         options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
     });
Run Code Online (Sandbox Code Playgroud)

官方网站上有一个示例https://learn.microsoft.com/en-us/dotnet/standard/datetime/system-text-json-support

JsonSerializerOptions options = new JsonSerializerOptions();
options.Converters.Add(new DateTimeConverterForCustomStandardFormatR());
Run Code Online (Sandbox Code Playgroud)

但是我怎样才能将它连接到 DI 以便在控制器中使用呢?

D-S*_*hih 22

我们可以尝试使用builder.Services.Configure<JsonOptions>.net core 6 在 DI 容器中设置序列化器设置

JsonOptions让我们配置 JSON 序列化设置,这可能会AddJsonOptions方法。

JsonOptions可能会在SourceCodeJsonOptions中使用与 DI 中的对象相同的对象。

using Microsoft.AspNetCore.Http.Json;

builder.Services.Configure<JsonOptions>(options =>
{
    options.SerializerOptions.Converters.Add(new DateTimeConverterForCustomStandardFormatR());
});
Run Code Online (Sandbox Code Playgroud)

我认为这一变化是基于微软希望通过 ASP.NET Core 引入最小化的 Web API在 .net 6 中

最小 API 的架构旨在创建具有最小依赖性的 HTTP API。它们非常适合仅在 ASP.NET Core 中包含最少文件、功能和依赖项的微服务和应用程序。