|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.IO; |
| 6 | +using System.Text; |
| 7 | +using System.Text.Json; |
| 8 | +using System.Threading; |
| 9 | +using System.Threading.Tasks; |
| 10 | +using Microsoft.Extensions.DependencyInjection; |
| 11 | +using Microsoft.Extensions.Options; |
| 12 | +using Microsoft.Extensions.Primitives; |
| 13 | + |
| 14 | +#nullable enable |
| 15 | + |
| 16 | +namespace Microsoft.AspNetCore.Http.Json |
| 17 | +{ |
| 18 | + public static class HttpRequestJsonExtensions |
| 19 | + { |
| 20 | + /// <summary> |
| 21 | + /// Read JSON from the request and deserialize to the specified type. |
| 22 | + /// If the request's content-type is not a known JSON type then an error will be thrown. |
| 23 | + /// </summary> |
| 24 | + /// <typeparam name="TValue">The type of object to read.</typeparam> |
| 25 | + /// <param name="request">The request to read from.</param> |
| 26 | + /// <param name="cancellationToken">A <see cref="CancellationToken"/> used to cancel the operation.</param> |
| 27 | + /// <returns>The task object representing the asynchronous operation.</returns> |
| 28 | + public static ValueTask<TValue> ReadFromJsonAsync<TValue>( |
| 29 | + this HttpRequest request, |
| 30 | + CancellationToken cancellationToken = default) |
| 31 | + { |
| 32 | + return request.ReadFromJsonAsync<TValue>(options: null, cancellationToken); |
| 33 | + } |
| 34 | + |
| 35 | + /// <summary> |
| 36 | + /// Read JSON from the request and deserialize to the specified type. |
| 37 | + /// If the request's content-type is not a known JSON type then an error will be thrown. |
| 38 | + /// </summary> |
| 39 | + /// <typeparam name="TValue">The type of object to read.</typeparam> |
| 40 | + /// <param name="request">The request to read from.</param> |
| 41 | + /// <param name="options">The serializer options use when deserializing the content.</param> |
| 42 | + /// <param name="cancellationToken">A <see cref="CancellationToken"/> used to cancel the operation.</param> |
| 43 | + /// <returns>The task object representing the asynchronous operation.</returns> |
| 44 | + public static async ValueTask<TValue> ReadFromJsonAsync<TValue>( |
| 45 | + this HttpRequest request, |
| 46 | + JsonSerializerOptions? options, |
| 47 | + CancellationToken cancellationToken = default) |
| 48 | + { |
| 49 | + if (request == null) |
| 50 | + { |
| 51 | + throw new ArgumentNullException(nameof(request)); |
| 52 | + } |
| 53 | + |
| 54 | + if (!request.HasJsonContentType(out var charset)) |
| 55 | + { |
| 56 | + throw CreateContentTypeError(request); |
| 57 | + } |
| 58 | + |
| 59 | + options ??= ResolveSerializerOptions(request.HttpContext); |
| 60 | + |
| 61 | + var encoding = GetEncodingFromCharset(charset); |
| 62 | + var (inputStream, usesTranscodingStream) = GetInputStream(request.HttpContext, encoding); |
| 63 | + |
| 64 | + try |
| 65 | + { |
| 66 | + return await JsonSerializer.DeserializeAsync<TValue>(inputStream, options, cancellationToken); |
| 67 | + } |
| 68 | + finally |
| 69 | + { |
| 70 | + if (usesTranscodingStream) |
| 71 | + { |
| 72 | + await inputStream.DisposeAsync(); |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + /// <summary> |
| 78 | + /// Read JSON from the request and deserialize to the specified type. |
| 79 | + /// If the request's content-type is not a known JSON type then an error will be thrown. |
| 80 | + /// </summary> |
| 81 | + /// <param name="request">The request to read from.</param> |
| 82 | + /// <param name="type">The type of object to read.</param> |
| 83 | + /// <param name="cancellationToken">A <see cref="CancellationToken"/> used to cancel the operation.</param> |
| 84 | + /// <returns>The task object representing the asynchronous operation.</returns> |
| 85 | + public static ValueTask<object?> ReadFromJsonAsync( |
| 86 | + this HttpRequest request, |
| 87 | + Type type, |
| 88 | + CancellationToken cancellationToken = default) |
| 89 | + { |
| 90 | + return request.ReadFromJsonAsync(type, options: null, cancellationToken); |
| 91 | + } |
| 92 | + |
| 93 | + /// <summary> |
| 94 | + /// Read JSON from the request and deserialize to the specified type. |
| 95 | + /// If the request's content-type is not a known JSON type then an error will be thrown. |
| 96 | + /// </summary> |
| 97 | + /// <param name="request">The request to read from.</param> |
| 98 | + /// <param name="type">The type of object to read.</param> |
| 99 | + /// <param name="options">The serializer options use when deserializing the content.</param> |
| 100 | + /// <param name="cancellationToken">A <see cref="CancellationToken"/> used to cancel the operation.</param> |
| 101 | + /// <returns>The task object representing the asynchronous operation.</returns> |
| 102 | + public static async ValueTask<object?> ReadFromJsonAsync( |
| 103 | + this HttpRequest request, |
| 104 | + Type type, |
| 105 | + JsonSerializerOptions? options, |
| 106 | + CancellationToken cancellationToken = default) |
| 107 | + { |
| 108 | + if (request == null) |
| 109 | + { |
| 110 | + throw new ArgumentNullException(nameof(request)); |
| 111 | + } |
| 112 | + if (type == null) |
| 113 | + { |
| 114 | + throw new ArgumentNullException(nameof(type)); |
| 115 | + } |
| 116 | + |
| 117 | + if (!request.HasJsonContentType(out var charset)) |
| 118 | + { |
| 119 | + throw CreateContentTypeError(request); |
| 120 | + } |
| 121 | + |
| 122 | + options ??= ResolveSerializerOptions(request.HttpContext); |
| 123 | + |
| 124 | + var encoding = GetEncodingFromCharset(charset); |
| 125 | + var (inputStream, usesTranscodingStream) = GetInputStream(request.HttpContext, encoding); |
| 126 | + |
| 127 | + try |
| 128 | + { |
| 129 | + return await JsonSerializer.DeserializeAsync(inputStream, type, options, cancellationToken); |
| 130 | + } |
| 131 | + finally |
| 132 | + { |
| 133 | + if (usesTranscodingStream) |
| 134 | + { |
| 135 | + await inputStream.DisposeAsync(); |
| 136 | + } |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + private static JsonSerializerOptions ResolveSerializerOptions(HttpContext httpContext) |
| 141 | + { |
| 142 | + // Attempt to resolve options from DI then fallback to default options |
| 143 | + return httpContext.RequestServices?.GetService<IOptions<JsonOptions>>()?.Value?.SerializerOptions ?? JsonOptions.DefaultSerializerOptions; |
| 144 | + } |
| 145 | + |
| 146 | + private static InvalidOperationException CreateContentTypeError(HttpRequest request) |
| 147 | + { |
| 148 | + return new InvalidOperationException($"Unable to read the request as JSON because the request content type '{request.ContentType}' is not a known JSON content type."); |
| 149 | + } |
| 150 | + |
| 151 | + private static (Stream inputStream, bool usesTranscodingStream) GetInputStream(HttpContext httpContext, Encoding? encoding) |
| 152 | + { |
| 153 | + if (encoding == null || encoding.CodePage == Encoding.UTF8.CodePage) |
| 154 | + { |
| 155 | + return (httpContext.Request.Body, false); |
| 156 | + } |
| 157 | + |
| 158 | + var inputStream = Encoding.CreateTranscodingStream(httpContext.Request.Body, encoding, Encoding.UTF8, leaveOpen: true); |
| 159 | + return (inputStream, true); |
| 160 | + } |
| 161 | + |
| 162 | + private static Encoding? GetEncodingFromCharset(StringSegment charset) |
| 163 | + { |
| 164 | + if (charset.Equals("utf-8", StringComparison.OrdinalIgnoreCase)) |
| 165 | + { |
| 166 | + // This is an optimization for utf-8 that prevents the Substring caused by |
| 167 | + // charset.Value |
| 168 | + return Encoding.UTF8; |
| 169 | + } |
| 170 | + |
| 171 | + try |
| 172 | + { |
| 173 | + // charset.Value might be an invalid encoding name as in charset=invalid. |
| 174 | + return charset.HasValue ? Encoding.GetEncoding(charset.Value) : null; |
| 175 | + } |
| 176 | + catch (Exception ex) |
| 177 | + { |
| 178 | + throw new InvalidOperationException($"Unable to read the request as JSON because the request content type charset '{charset}' is not a known encoding.", ex); |
| 179 | + } |
| 180 | + } |
| 181 | + } |
| 182 | +} |
0 commit comments