使用ASP.NET Core 2.1在控制器上配置输入/输出格式化程序 [英] Configure input/output formatters on controllers with ASP.NET Core 2.1
问题描述
我正在将旧的ASP.NET WebAPI 2.1项目重写为ASP.NET Core MVC 2.1.我面临的问题之一是关于移植服务的旧行为,该行为通过实现IControllerConfiguration接口的自定义属性来配置输入和输出格式化程序.除了使用AddMvc(options)方法在全局级别注入格式化程序外,我无法找到该接口的替代品,也无法在控制器基础上配置格式化程序的任何替代方法.
I am in the process of rewriting an old ASP.NET WebAPI 2.1 project to ASP.NET Core MVC 2.1. One of the problem I am facing is about porting the old behavior of the service which configure the input and output formatters through custom attributes whom implement IControllerConfiguration interface. I have not been able to find a replacement for this interface nor any alternative to configure formatters on controller-basis, other than injecting them at global level with the AddMvc(options) method.
推荐答案
实际上,我找到了一种方法.我创建了一个属性,该属性也实现了IResultFilter,这是其中发生魔术的OnResultExecuting方法:
Actually I found a way. I created an attribute which also implements IResultFilter and here is the OnResultExecuting method, where the magic happens:
public void OnResultExecuting(ResultExecutingContext context)
{
var objectResult = context.Result as ObjectResult;
if (objectResult != null)
{
var serializerSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver()
};
var jsonFormatter = new JsonOutputFormatter(
serializerSettings,
ArrayPool<char>.Shared);
objectResult.Formatters.Add(jsonFormatter);
}
}
基本上,在这里,我将在每个对象结果中注入自定义JSON格式器,然后将其发送到客户端.似乎(但是我没有找到任何相关文档)以这种方式,ASP.NET Core MVC比全局定义的格式化程序更喜欢注入的格式化程序.
Basically here I am injecting a custom JSON formatter in every object result, before it is sent to the client. It appears (but I did not find any documentation about this) that in this way ASP.NET Core MVC prefers the injected formatter over the globally defined one.
我希望这对其他人有帮助,因为我一直在为此苦苦挣扎...
I hopes it helps other because I was struggling on this...
这篇关于使用ASP.NET Core 2.1在控制器上配置输入/输出格式化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!