using Microsoft.AspNetCore.Mvc.Formatters; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.AspNetCore.Mvc.Formatters { public class RawJsonOutputFormatter : TextOutputFormatter { public RawJsonOutputFormatter() { this.SupportedMediaTypes.Add("application/json"); this.SupportedEncodings.Add(Encoding.UTF8); this.SupportedEncodings.Add(Encoding.Unicode); } public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) { if (context == null) throw new ArgumentNullException(nameof(context)); if (selectedEncoding == null) throw new ArgumentNullException(nameof(selectedEncoding)); using (var writer = context.WriterFactory(context.HttpContext.Response.Body, selectedEncoding)) { if (context.Object is string str) { writer.Write(str); } else if (context.Object is List list) { writer.Write('['); var index = 0; var last = list.Count - 1; for (var i = 0; i < list.Count; ++i) { writer.Write(list[i]); if(index != last) writer.Write(','); } writer.Write(']'); } else throw new InvalidOperationException(); await writer.FlushAsync(); } } protected override bool CanWriteType(Type type) { return type == typeof(string) || type == typeof(List); } } }