我还没有找到可以在控制器级别配置的任何内容,但我确实找到了一个解决方案,该解决方案涉及对您需要此功能的每个操作进行更改。在我的情况下,我需要自定义 JSON 序列化程序设置,可以像这样为输出完成:
[HttpGet]
public IActionResult Get()
{
...
return Json(result, _serializerSettings);
}
并喜欢这样的输入:
[HttpPost]
public IActionResult Post([FromBodyCustomSerializationSettings]MyPostDto postDto)
{
...
}
class FromBodyCustomSerializationSettingsAttribute : ModelBinderAttribute
{
public FromBodyCustomSerializationSettingsAttribute() : base(typeof(MyModelBinder))
{
BindingSource = BindingSource.Body;
}
}
class MyModelBinder : IModelBinder
{
private readonly BodyModelBinder _bodyModelBinder;
public MyModelBinder(IHttpRequestStreamReaderFactory readerFactory, ILoggerFactory loggerFactory, IOptions<MvcOptions> options, IOptions<MvcJsonOptions> jsonOptions, ArrayPool<char> charPool, ObjectPoolProvider objectPoolProvider)
{
var formatters = options.Value.InputFormatters.ToList();
int jsonFormatterIndex = formatters.FirstIndexOf(formatter => formatter is JsonInputFormatter);
JsonSerializerSettings myCustomSettings = ...
formatters[jsonFormatterIndex] = new JsonInputFormatter(loggerFactory.CreateLogger("MyCustomJsonFormatter"), myCustomSettings, charPool, objectPoolProvider, options.Value, jsonOptions.Value);
_bodyModelBinder = new BodyModelBinder(formatters, readerFactory, loggerFactory, options.Value);
}
public Task BindModelAsync(ModelBindingContext bindingContext)
{
return _bodyModelBinder.BindModelAsync(bindingContext);
}
}