c# - 设置 Asp.Net Core MVC Json 选项

标签 c# json asp.net-core .net-core json.net

我的项目中有一个名为 AC 的类,它有一个类型为 IPEndPoint 的属性 Address。这种类型以及 IPAddress 因默认情况下无法序列化为 JSON 而臭名昭著。由于我需要序列化我的类,我实现了两个自定义转换器:IPAddressConverterIPEndPointConverter。为了让 Newtonsoft 使用这两个转换器,我创建了这个类:

public sealed class CustomSettings : JsonSerializerSettings
{
    public CustomSettings() : base()
    {
        this.Converters.Add(new IPAddressConverter());
        this.Converters.Add(new IPEndPointConverter());
        this.TypeNameHandling = TypeNameHandling.Auto;
    }
} 

..我在我的 Main 中这样使用它:

Newtonsoft.Json.JsonConvert.DefaultSettings = () => new CustomSettings();

现在我正在尝试将 API 添加到我的程序中。我已经创建了一个 .Net Core Web API 项目并将其成功集成到我的程序中。但是,当我尝试编写一个 POST 方法时,问题出现了,该方法需要来自请求正文的 JSON 格式的 AC 实例。序列化程序无法转换 IPEndPoint,因此 AC 的值始终为 null

关于 .Net Core API 配置的信息非常少。谁能告诉我如何将这些相同的设置传递给 MVC 的序列化程序?

编辑

我找到了一种方法(某种程度上)。事实证明,您可以在 ConfigureServices 方法中设置 JSON 选项。

我试图通过这样做来修改 MVC 的序列化程序的设置,就像我对程序的其余部分所做的那样:

services.AddMvc().AddJsonOptions(options => options.SerializerSettings = new CustomSettings());

但是,这不起作用,因为 options.SerializerSettings 是只读的。

可以一个接一个地传递转换器,但我更希望它们都从一个地方(CustomSettings 类)进行管理。这可能吗?

最佳答案

创建一个扩展方法来封装你想要配置的内容

public static void AddCustomSettings(this Newtonsoft.Json.JsonSerializerSettings settings) {
    settings.Converters.Add(new IPAddressConverter());
    settings.Converters.Add(new IPEndPointConverter());
    settings.TypeNameHandling = TypeNameHandling.Auto;
}

并在ConfigureServices中配置

services.AddJsonOptions(options => options.SerializerSettings.AddCustomSettings());

关于c# - 设置 Asp.Net Core MVC Json 选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44031915/

相关文章:

javascript - 使用jquery读取json数据时遇到问题

c# - 在 Windows 窗体应用程序中托管 ASP.NET Core API

docker - Web API端点可与docker-compose.yml一起使用,但不适用于仅使用Dockerfile进行构建和运行的情况

c# - c# 项目中没有 main()

json - WCF WebFaultException 异常详细信息

c# - 返回玩家组合的有效方法

javascript - 使用 jQuery 解析 JSON,检索两个变量。

c# - 如何在 Controller 以外的地方调用 SignalR Clients.All.InvokeAsync()?

c# - 如何正确解码重音字符以显示

C#正则表达式匹配