ASP.NET Core 3.1 中使用 Newtonsoft.JSON 的自定义 JsonConverter 属性不适用于 Json.Serialize()

Custom JsonConverter attributes not working with Json.Serialize() using Newtonsoft.JSON in ASP.NET Core 3.1

我想使用 Newtonsoft Json.NET 在 ASP.NET Core 3.1 应用程序中执行 de/serialization。我在启动 ConfigureServices 代码中添加了以下内容:

services.AddMvc().AddNewtonsoftJson();

我有一个带有自定义序列化属性的 MVC 模型:

public class MyModel {
    [Newtonsoft.Json.JsonConverter(typeof(MyCustomJsonConverter))]
    public DateTime MyProperty {get; set;}
}

在我看来,我将其序列化为 JSON:

<script>
    someJsFunction(@Json.Serialize(Model));
</script>

但它不使用 MyCustomJsonConverter。 MyCustomJsonConverter 中未命中断点。

答案可能是添加到全局 Json 设置:

services.AddMvc().AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.Converters = new List<JsonConverter>()
        {
            new MyCustomJsonConverter()
        };

    });

但随后 MyCustomJsonConverter 将应用于每个 DateTime 属性,而不仅仅是应用了属性的那些。我也可以使用 JSON.Serialize 重载:

<script>
    someJsFunction(@Json.Serialize(Model, new JsonSerializerSettings()
                                           {
                                               Converters = new List<JsonConverter> { new MyCustomJsonConverter()},       
                                           }
                                  ));
</script>

但是我不想每次调用都这样。我很确定这些 JsonConverter 属性在从 3.0 中的 Newtonsoft Json.NET 切换之前自己可以正常工作。知道我做错了什么吗?

在您看来,为 Newtonsoft 添加 using 并使用它的 Serializer。

@using Newtonsoft.Json;

...

..(@JsonConvert.SerializeObject(Model))

不起作用的原因是您使用的序列化程序来自不同的库,一个来自 Microsoft.AspNetCore.Mvc.Rendering,另一个来自 Newtonsoft.Json