Configure input/output formatters on controllers with ASP.NET Core 2.1

前端 未结 2 1126
予麋鹿
予麋鹿 2020-12-20 05:43

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 w

2条回答
  •  囚心锁ツ
    2020-12-20 06:10

    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.Shared);
    
        objectResult.Formatters.Add(jsonFormatter);
      }
    }
    

    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...

提交回复
热议问题