AspNet Core-控制器级别的输入/输出JSON序列化设置 [英] AspNet Core - input/output JSON serialization settings at Controller Level
问题描述
我的应用程序需要(几乎是默认的)JSON序列化设置:
My application requires the (almost default) JSON serialization settings:
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;
options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
});
仅对于一个控制器,我需要对两种输入都使用不同的命名策略(其中,我将模型绑定与[FromBody] myComplexObject
一起使用,将输出与
For one controller only, I need to use a different naming strategy for both input (where I use model binding with [FromBody] myComplexObject
and output with
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
我的问题实际上与 Web相同API:在操作或控制器级别配置JSON序列化程序设置,但我要的是AspNet Core 2.2+,其中不再存在IControllerConfiguration
.
My question is virtually identical to Web API: Configure JSON serializer settings on action or controller level with the exception that I'm asking for AspNet Core 2.2+, in which IControllerConfiguration
is no longer existent.
The Core 2.1+ equivalent question has a response here: Configure input/output formatters on controllers with ASP.NET Core 2.1
那里的答案似乎有些零散或不完整-很难想象没有比这更简单的方法了. 有人会对如何在单个控制器内的所有输入和输出中使用DefaultContractResolver产生想法吗?
The answers there appear slightly fragmented or incomplete - it's hard to imagine that there is no easier way to achieve this. Would anyone have an idea on how to use a DefaultContractResolver for all input and output within a single controller?
推荐答案
您链接的答案效果很好,但是您可以通过将其包装在可以应用于任何操作或控制器的属性中来进一步扩展该答案.例如:
The answer you link works well enough, but you can extend it further by wrapping it in an attribute that you can apply to any action or controller. For example:
public class JsonConfigFilterAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext context)
{
if (context.Result is ObjectResult objectResult)
{
var serializerSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver()
};
var jsonFormatter = new JsonOutputFormatter(
serializerSettings,
ArrayPool<char>.Shared);
objectResult.Formatters.Add(jsonFormatter);
}
base.OnResultExecuting(context);
}
}
然后将其添加到动作方法或控制器中
And just add it to action methods or controllers:
[JsonConfigFilter]
public ActionResult<Foo> SomeAction()
{
return new Foo
{
Bar = "hello"
};
}
这篇关于AspNet Core-控制器级别的输入/输出JSON序列化设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!