简体   繁体   English

ASP.NET Core 中每个控制器的不同 JSON 反序列化设置

[英]Different JSON deserialization settings per controller in ASP.NET Core

I am trying to set different JsonSerializerOptions for specific controllers.我正在尝试为特定控制器设置不同的JsonSerializerOptions Specifically, I want to set ReferenceHandler = ReferenceHandler.Preserve for those controllers only, and inherit the rest of the serializer options from some static instance.具体来说,我只想为这些控制器设置ReferenceHandler = ReferenceHandler.Preserve ,并从某个静态实例继承其余的序列化程序选项。

I'm looking for a way to do this at the controller level, using System.Text.Json on ASP.NET Core 6.0.我正在寻找一种在控制器级别执行此操作的方法,在 ASP.NET Core 6.0 上使用System.Text.Json

I was able to do this for serialization using an Action Filter using this solution: https://stackoverflow.com/a/56127866/2719183 , but I haven't been able to find a good solution to implement this for deserialization.我能够使用以下解决方案使用动作过滤器进行序列化: https ://stackoverflow.com/a/56127866/2719183,但我无法找到一个好的解决方案来实现反序列化。 For example, https://stackoverflow.com/a/66256442/2719183 , does not work for me because it requires an attribute for each parameter.例如, https://stackoverflow.com/a/66256442/2719183对我不起作用,因为它需要每个参数的属性。

How do I override an input formatter at the controller level?如何在控制器级别覆盖输入格式化程序?

There are two problems: serialization and deserialization.有两个问题:序列化和反序列化。

  1. Serialization.序列化。 This is relatively easy, you have to create action filter and inspect action result, if it is ObjectResult then you can set custom json formatter.这相对容易,您必须创建动作过滤器并检查动作结果,如果是ObjectResult那么您可以设置自定义 json 格式化程序。

  2. Deserialization/binding.反序列化/绑定。 This one is tricky, you'll need custom body binder (which can be configured to use custom json formatter), custom binder provider, custom binder source and custom IControllerModelConvention to selectively override binding source on actions.这很棘手,您需要自定义正文绑定器(可以配置为使用自定义 json 格式化程序)、自定义绑定器提供程序、自定义绑定器源和自定义IControllerModelConvention以选择性地覆盖操作上的绑定源。

This should work for simple scenarios when you don't use other filters or middlewares etc.当您不使用其他过滤器或中间件等时,这应该适用于简单的场景。

I'm not attaching any code, because it will be a dozen of classes.我没有附加任何代码,因为它将是十几个类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM