|
| 1 | +using System.Runtime.ExceptionServices; |
| 2 | +using System.Text; |
| 3 | +using System.Text.Encodings.Web; |
| 4 | +using System.Text.Json; |
| 5 | +using System.Text.Json.Serialization; |
| 6 | +using Microsoft.AspNetCore.Mvc; |
| 7 | +using Microsoft.AspNetCore.Mvc.Formatters; |
| 8 | +using Microsoft.Net.Http.Headers; |
| 9 | + |
| 10 | +namespace YS.Knife.Query.Demo.AspnetCore |
| 11 | +{ |
| 12 | + internal static class MediaTypeHeaderValues |
| 13 | + { |
| 14 | + public static readonly MediaTypeHeaderValue ApplicationJson |
| 15 | + = MediaTypeHeaderValue.Parse("application/json").CopyAsReadOnly(); |
| 16 | + |
| 17 | + public static readonly MediaTypeHeaderValue TextJson |
| 18 | + = MediaTypeHeaderValue.Parse("text/json").CopyAsReadOnly(); |
| 19 | + |
| 20 | + public static readonly MediaTypeHeaderValue ApplicationAnyJsonSyntax |
| 21 | + = MediaTypeHeaderValue.Parse("application/*+json").CopyAsReadOnly(); |
| 22 | + |
| 23 | + public static readonly MediaTypeHeaderValue ApplicationXml |
| 24 | + = MediaTypeHeaderValue.Parse("application/xml").CopyAsReadOnly(); |
| 25 | + |
| 26 | + public static readonly MediaTypeHeaderValue TextXml |
| 27 | + = MediaTypeHeaderValue.Parse("text/xml").CopyAsReadOnly(); |
| 28 | + |
| 29 | + public static readonly MediaTypeHeaderValue ApplicationAnyXmlSyntax |
| 30 | + = MediaTypeHeaderValue.Parse("application/*+xml").CopyAsReadOnly(); |
| 31 | + } |
| 32 | + |
| 33 | + /// <summary> |
| 34 | + /// A <see cref="TextOutputFormatter"/> for JSON content that uses <see cref="JsonSerializer"/>. |
| 35 | + /// </summary> |
| 36 | + public class SystemTextJsonOutputFormatter2 : TextOutputFormatter |
| 37 | + { |
| 38 | + /// <summary> |
| 39 | + /// Initializes a new <see cref="SystemTextJsonOutputFormatter"/> instance. |
| 40 | + /// </summary> |
| 41 | + /// <param name="jsonSerializerOptions">The <see cref="JsonSerializerOptions"/>.</param> |
| 42 | + public SystemTextJsonOutputFormatter2(JsonSerializerOptions jsonSerializerOptions) |
| 43 | + { |
| 44 | + SerializerOptions = jsonSerializerOptions; |
| 45 | + |
| 46 | + SupportedEncodings.Add(Encoding.UTF8); |
| 47 | + SupportedEncodings.Add(Encoding.Unicode); |
| 48 | + SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationJson); |
| 49 | + SupportedMediaTypes.Add(MediaTypeHeaderValues.TextJson); |
| 50 | + SupportedMediaTypes.Add(MediaTypeHeaderValues.ApplicationAnyJsonSyntax); |
| 51 | + } |
| 52 | + |
| 53 | + internal static SystemTextJsonOutputFormatter CreateFormatter(JsonOptions jsonOptions) |
| 54 | + { |
| 55 | + var jsonSerializerOptions = jsonOptions.JsonSerializerOptions; |
| 56 | + |
| 57 | + //jsonSerializerOptions. |
| 58 | + if (jsonSerializerOptions.Encoder is null) |
| 59 | + { |
| 60 | + // If the user hasn't explicitly configured the encoder, use the less strict encoder that does not encode all non-ASCII characters. |
| 61 | + jsonSerializerOptions = new JsonSerializerOptions(jsonSerializerOptions) |
| 62 | + { |
| 63 | + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, |
| 64 | + }; |
| 65 | + } |
| 66 | + |
| 67 | + return new SystemTextJsonOutputFormatter(jsonSerializerOptions); |
| 68 | + } |
| 69 | + |
| 70 | + /// <summary> |
| 71 | + /// Gets the <see cref="JsonSerializerOptions"/> used to configure the <see cref="JsonSerializer"/>. |
| 72 | + /// </summary> |
| 73 | + /// <remarks> |
| 74 | + /// A single instance of <see cref="SystemTextJsonOutputFormatter"/> is used for all JSON formatting. Any |
| 75 | + /// changes to the options will affect all output formatting. |
| 76 | + /// </remarks> |
| 77 | + public JsonSerializerOptions SerializerOptions { get; } |
| 78 | + |
| 79 | + /// <inheritdoc /> |
| 80 | + public sealed override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) |
| 81 | + { |
| 82 | + if (context == null) |
| 83 | + { |
| 84 | + throw new ArgumentNullException(nameof(context)); |
| 85 | + } |
| 86 | + |
| 87 | + if (selectedEncoding == null) |
| 88 | + { |
| 89 | + throw new ArgumentNullException(nameof(selectedEncoding)); |
| 90 | + } |
| 91 | + |
| 92 | + var httpContext = context.HttpContext; |
| 93 | + |
| 94 | + // context.ObjectType reflects the declared model type when specified. |
| 95 | + // For polymorphic scenarios where the user declares a return type, but returns a derived type, |
| 96 | + // we want to serialize all the properties on the derived type. This keeps parity with |
| 97 | + // the behavior you get when the user does not declare the return type and with Json.Net at least at the top level. |
| 98 | + var objectType = context.Object?.GetType() ?? context.ObjectType ?? typeof(object); |
| 99 | + |
| 100 | + var responseStream = httpContext.Response.Body; |
| 101 | + if (selectedEncoding.CodePage == Encoding.UTF8.CodePage) |
| 102 | + { |
| 103 | + await JsonSerializer.SerializeAsync(responseStream, context.Object, objectType, GetJsonSerializerOptions(context)); |
| 104 | + await responseStream.FlushAsync(); |
| 105 | + } |
| 106 | + else |
| 107 | + { |
| 108 | + // JsonSerializer only emits UTF8 encoded output, but we need to write the response in the encoding specified by |
| 109 | + // selectedEncoding |
| 110 | + var transcodingStream = Encoding.CreateTranscodingStream(httpContext.Response.Body, selectedEncoding, Encoding.UTF8, leaveOpen: true); |
| 111 | + |
| 112 | + ExceptionDispatchInfo exceptionDispatchInfo = null; |
| 113 | + try |
| 114 | + { |
| 115 | + await JsonSerializer.SerializeAsync(transcodingStream, context.Object, objectType, GetJsonSerializerOptions(context)); |
| 116 | + await transcodingStream.FlushAsync(); |
| 117 | + } |
| 118 | + catch (Exception ex) |
| 119 | + { |
| 120 | + // TranscodingStream may write to the inner stream as part of it's disposal. |
| 121 | + // We do not want this exception "ex" to be eclipsed by any exception encountered during the write. We will stash it and |
| 122 | + // explicitly rethrow it during the finally block. |
| 123 | + exceptionDispatchInfo = ExceptionDispatchInfo.Capture(ex); |
| 124 | + } |
| 125 | + finally |
| 126 | + { |
| 127 | + try |
| 128 | + { |
| 129 | + await transcodingStream.DisposeAsync(); |
| 130 | + } |
| 131 | + catch when (exceptionDispatchInfo != null) |
| 132 | + { |
| 133 | + } |
| 134 | + |
| 135 | + exceptionDispatchInfo?.Throw(); |
| 136 | + } |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + protected virtual JsonSerializerOptions GetJsonSerializerOptions(OutputFormatterWriteContext context) |
| 141 | + { |
| 142 | + var converters = GetDynamicConverters(context.HttpContext); |
| 143 | + if (converters == null || converters.Length == 0) |
| 144 | + { |
| 145 | + return this.SerializerOptions; |
| 146 | + } |
| 147 | + else |
| 148 | + { |
| 149 | + var newSerializerOptions = new JsonSerializerOptions(this.SerializerOptions); |
| 150 | + Array.ForEach(converters, p => newSerializerOptions.Converters.Add(p)); |
| 151 | + |
| 152 | + return newSerializerOptions; |
| 153 | + } |
| 154 | + } |
| 155 | + private JsonConverter[] GetDynamicConverters(HttpContext context) |
| 156 | + { |
| 157 | + //TODO |
| 158 | + return null; |
| 159 | + } |
| 160 | + |
| 161 | + private SelectInfo GetSelectInfo(HttpContext context) |
| 162 | + { |
| 163 | + var text = context.Items["__query_select"] as string; |
| 164 | + if (string.IsNullOrEmpty(text)) |
| 165 | + { |
| 166 | + return null; |
| 167 | + } |
| 168 | + else |
| 169 | + { |
| 170 | + return SelectInfo.Parse(text); |
| 171 | + } |
| 172 | + } |
| 173 | + } |
| 174 | + |
| 175 | + public class FilterColumnJsonFormatter : SystemTextJsonOutputFormatter |
| 176 | + { |
| 177 | + public FilterColumnJsonFormatter(JsonSerializerOptions jsonSerializerOptions) : base(jsonSerializerOptions) |
| 178 | + { |
| 179 | + } |
| 180 | + public override bool CanWriteResult(OutputFormatterCanWriteContext context) |
| 181 | + { |
| 182 | + return base.CanWriteResult(context); |
| 183 | + } |
| 184 | + protected override bool CanWriteType(Type type) |
| 185 | + { |
| 186 | + return base.CanWriteType(type); |
| 187 | + } |
| 188 | + public override Task WriteAsync(OutputFormatterWriteContext context) |
| 189 | + { |
| 190 | + var selectInfo = GetSelectInfo(context.HttpContext); |
| 191 | + return base.WriteAsync(context); |
| 192 | + } |
| 193 | + private SelectInfo GetSelectInfo(HttpContext context) |
| 194 | + { |
| 195 | + var text = context.Items["__query_select"] as string; |
| 196 | + if (string.IsNullOrEmpty(text)) |
| 197 | + { |
| 198 | + return null; |
| 199 | + } |
| 200 | + else |
| 201 | + { |
| 202 | + return SelectInfo.Parse(text); |
| 203 | + } |
| 204 | + } |
| 205 | + } |
| 206 | +} |
0 commit comments