设置 JsonConvert.DefaultSettings asp net core 2.0 未按预期工作 [英] Setting JsonConvert.DefaultSettings asp net core 2.0 not working as expected

查看:27
本文介绍了设置 JsonConvert.DefaultSettings asp net core 2.0 未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Startup.cs 中有以下代码,并希望它覆盖默认的序列化选项.我希望它覆盖整个 asp net core 2.0 项目中的每个序列化,但是操作返回值不正确,我认为这个全局属性在 core 2.0 中不起作用

I have following code inside Startup.cs and expecting it to override default serialization options. I want it to override every single serialization throughout my asp net core 2.0 project, but action return value that is not correct, I think this global property is not working in core 2.0

我在app.UseMvc()之前把它写在Configure里;

I have it written inside Configure exactly before app.UseMvc();

JsonConvert.DefaultSettings = () => new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.Objects,
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Converters = new List<JsonConverter> { new StringEnumConverter() }
            };

推荐答案

在 ASP.NET Core 中,这是在 Startup.ConfigureServices 中连接应用程序上的服务时配置的.AddMvc() 扩展返回的 IMvcBuilder 有一个流畅的 AddJsonOptions(Action<MvcJsonOptions>) 扩展.MvcJsonOptions 公开了一个 SerializerSettings 属性,您可以在操作代码中配置该属性.

In ASP.NET Core, this is configured when wiring up the services on the application in Startup.ConfigureServices. There is an fluent AddJsonOptions(Action<MvcJsonOptions>) extension to the IMvcBuilder returned by the AddMvc() extension. MvcJsonOptions exposes a SerializerSettings property which you can configure in your action code.

因此不是在注册 MVC 之前配置一次,而是作为 MVC 注册的一部分完成.

So instead of configuring once before registering MVC, it's done as part of the MVC registration.

包含您的设置的示例:

services.AddMvc()
  .AddJsonOptions( options =>
  {
    options.SerializerSettings.Formatting = Formatting.Indented;
    options.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects;
    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    options.SerializerSettings.Converters.Add(new StringEnumConverter());
  });

这篇关于设置 JsonConvert.DefaultSettings asp net core 2.0 未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆