Generic method of modifying JSON before being returned to client

后端 未结 2 527
渐次进展
渐次进展 2020-12-07 03:54

I\'m after a generic method that allows me to modify the JSON of an object being returned to the client, specifically the removal of certain properties in returned objects.

2条回答
  •  忘掉有多难
    2020-12-07 04:18

    In typical fashion, the process of posing the question caused me to take a fresh take on the problem.

    I have found one possible work-around: creating a custom MediaTypeFormatter.

    With help from here and here, a potential solution:-

    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net.Http.Formatting;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Test
    {
        public class TestFormatter : MediaTypeFormatter
        {
            public TestFormatter()
            {
                SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
            }
    
            public override bool CanReadType(Type type)
            {
                return false;
            }
    
            public override bool CanWriteType(Type type)
            {
                return true;
            }
    
            public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
            {
                JsonSerializer serializer = new JsonSerializer();
    
                serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
                serializer.Converters.Add(new TestConverter());
    
                return Task.Factory.StartNew(() =>
                {
                    using (JsonTextWriter jsonTextWriter = new JsonTextWriter(new StreamWriter(writeStream, Encoding.ASCII)) { CloseOutput = false })
                    {
                        serializer.Serialize(jsonTextWriter, value);
                        jsonTextWriter.Flush();
                    }
                });
            }
        }
    }
    

    and then configure the app to use it:-

    // insert at 0 so it runs before System.Net.Http.Formatting.JsonMediaTypeFormatter
    config.Formatters.Insert(0, new TestFormatter());
    

    This creates a new instance of my JsonConverter for each request, which in combination with the other fixes in the original post, seem to solve the issue.

    This is probably not the best way of doing this, so I'll leave this open for some better suggestions, or until I realise why this isn't going to work.

提交回复
热议问题