设置JsonConvert.DefaultSettings ASP Net Core 2.0无法按预期工作 [英] Setting JsonConvert.DefaultSettings asp net core 2.0 not working as expected
问题描述
我在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屋!