< Summary

Information
Class: NanoRoute.JsonErrorDetailsOptions
Assembly: NanoRoute.dll
File(s): /home/runner/work/nanoroute/nanoroute/Src/NanoRoute/Public/Extensions/NanoRouteJsonExtensions.cs
Line coverage
100%
Covered lines: 5
Uncovered lines: 0
Coverable lines: 5
Total lines: 934
Line coverage: 100%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBlocks covered Blocks not covered
JsonErrorDetailsOptions()30

File(s)

/home/runner/work/nanoroute/nanoroute/Src/NanoRoute/Public/Extensions/NanoRouteJsonExtensions.cs

#LineLine coverage
 1/********************************************************************************
 2* NanoRouteJsonExtensions.cs                                                    *
 3*                                                                               *
 4* Author: Denes Solti                                                           *
 5********************************************************************************/
 6using System;
 7using System.Collections.Generic;
 8using System.Diagnostics;
 9using System.Diagnostics.CodeAnalysis;
 10using System.IO;
 11using System.Net;
 12using System.Net.Http;
 13using System.Net.Mime;
 14using System.Text;
 15using System.Text.Json;
 16using System.Text.Json.Serialization.Metadata;
 17
 18namespace NanoRoute
 19{
 20    using Internals;
 21    using Properties;
 22
 23    /// <summary>
 24    /// Configures JSON error responses and exception normalization for a JSON error-details middleware registration.
 25    /// </summary>
 26    /// <remarks>
 27    /// <see cref="NanoRouteJsonExtensions.AddJsonErrorDetails{TBuilder}(TBuilder, Action{JsonErrorDetailsOptions})"/>
 28    /// snapshots these options when the middleware is registered. Because this type derives from
 29    /// <see cref="ExceptionHandlingOptions"/>, the same callback can configure both JSON error rendering and the
 30    /// internally registered exception handler.
 31    /// </remarks>
 32    /// <example>
 33    /// <code>
 34    /// builder.AddJsonErrorDetails(options =&gt;
 35    /// {
 36    ///     options.PopulateErrorInfo = true;
 37    ///     options.Map&lt;NotSupportedException&gt;
 38    ///     (
 39    ///         static ex =&gt; new HttpRequestException("Not supported", ex, HttpStatusCode.BadRequest)
 40    ///     );
 41    /// });
 42    /// </code>
 43    /// </example>
 44    public sealed class JsonErrorDetailsOptions : ExceptionHandlingOptions
 45    {
 46        /// <summary>
 47        /// Gets or sets a value indicating whether developer-facing diagnostic details should be included in JSON error
 48        /// </summary>
 49        /// <remarks>
 50        /// Diagnostic details may contain exception messages or stack traces. Keep this value <see langword="false"/>
 51        /// for production responses unless the caller is trusted to see those details.
 52        /// </remarks>
 53        /// <example>
 54        /// <code>
 55        /// builder.AddJsonErrorDetails(options =&gt;
 56        /// {
 57        ///     options.PopulateErrorInfo = true;
 58        /// });
 59        /// </code>
 60        /// </example>
 61        public bool PopulateErrorInfo { get; set; }
 62
 63        /// <summary>
 64        /// Gets or sets the JSON serialization metadata used for <see cref="ErrorDetails"/> responses.
 65        /// </summary>
 66        /// <remarks>
 67        /// Replace this value to use custom source-generated metadata, property naming, converters, or other
 68        /// serializer behavior for the error payload.
 69        /// </remarks>
 70        /// <exception cref="ArgumentNullException">Thrown when the assigned value is <see langword="null"/>.</exception
 71        /// <example>
 72        /// <code>
 73        /// builder.AddJsonErrorDetails(options =&gt;
 74        /// {
 75        ///     options.ErrorDetailsTypeInfo = MyJsonContext.Default.ErrorDetails;
 76        /// });
 77        /// </code>
 78        /// </example>
 79        public JsonTypeInfo<ErrorDetails> ErrorDetailsTypeInfo
 80        {
 81            get;
 82            set
 183            {
 184                Ensure.NotNull(value);
 185                field = value;
 186            }
 187        } = ErrorDetails.JsonTypeInfo;
 88    }
 89
 90
 91    /// <summary>
 92    /// Adds JSON-focused helpers for request body binding, structured error responses, and JSON responses.
 93    /// </summary>
 94    /// <remarks>
 95    /// These helpers are optional conveniences on top of the core routing pipeline. They are implemented as
 96    /// extension methods on <see cref="RouteScopeBuilder"/> and <see cref="HttpResponseMessage"/>.
 97    /// </remarks>
 98    /// <example>
 99    /// <code>
 100    /// builder
 101    ///     .AddJsonErrorDetails()
 102    ///     .AddJsonBody(typeof(CreateUserRequest), "body")
 103    ///     .AddHandler("POST", "/users/", (context, _) =&gt; Results.Ok(context.Parameters["body"]));
 104    /// </code>
 105    /// </example>
 106    public static class NanoRouteJsonExtensions
 107    {
 108        private const string JSON_MEDIA_TYPE =
 109#if NETSTANDARD2_1_OR_GREATER
 110            MediaTypeNames.Application.Json;
 111#else
 112            "application/json";
 113#endif
 114        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
 115        private static readonly Action<JsonErrorDetailsOptions> s_noopConfigure = static _ => { };
 116
 117        private static RequestHandlerDelegate CreateJsonBodyHandler(JsonTypeInfo typeInfo, string paramName)
 118        {
 119            Ensure.NotNull(typeInfo);
 120            Ensure.NotNull(paramName);
 121
 122            return async (RequestContext context, CallNextHandlerDelegate next) =>
 123            {
 124                context.Cancellation.ThrowIfCancellationRequested();
 125
 126                if (context.Request.Content is not { } content)
 127                {
 128                    BadRequest(Resources.ERR_MISSING_BODY);
 129                    return null!;
 130                }
 131
 132                if (!JSON_MEDIA_TYPE.Equals(content.Headers.ContentType?.MediaType, StringComparison.OrdinalIgnoreCase))
 133                    BadRequest(Resources.ERR_BAD_CONTENT_TYPE);
 134
 135                using Stream contentStream = await content.ReadAsStreamAsync().ConfigureAwait(false);
 136
 137                object? body = null;
 138
 139                try
 140                {
 141                    body = await JsonSerializer.DeserializeAsync(contentStream, typeInfo, context.Cancellation).Configur
 142                }
 143                catch (JsonException ex)
 144                {
 145                    BadRequest(ex.Message);
 146                }
 147
 148                context.Parameters[paramName] = body;
 149
 150                return await next().ConfigureAwait(false);
 151            };
 152
 153            [DoesNotReturn]
 154            static void BadRequest(string error) => HttpRequestException.Throw(HttpStatusCode.BadRequest, Resources.ERR_
 155        }
 156
 157        extension<TBuilder>(TBuilder routeScopeBuilder) where TBuilder : RouteScopeBuilder
 158        {
 159            /// <summary>
 160            /// Deserializes JSON request bodies into a route parameter for the selected HTTP methods.
 161            /// </summary>
 162            /// <param name="verbs">The HTTP methods that should require a JSON body.</param>
 163            /// <param name="pattern">
 164            /// The route pattern where the JSON-binding middleware should be inserted. Use <c>/</c> to apply it
 165            /// to the whole pipeline, or a narrower prefix/exact pattern to scope body binding to selected routes.
 166            /// </param>
 167            /// <param name="typeInfo">The metadata used to deserialize the request body.</param>
 168            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 169            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 170            /// <remarks>
 171            /// Requests without content, requests with a non-JSON content type, and requests with invalid JSON throw
 172            /// <see cref="HttpRequestException"/>. Add AddJsonErrorDetails to translate those into
 173            /// structured HTTP error responses. The deserialized body is written into
 174            /// <see cref="RequestContext.Parameters"/>, and an existing value with the same key is overwritten.
 175            /// </remarks>
 176            /// <example>
 177            /// <code>
 178            /// routerBuilder
 179            ///     .AddJsonErrorDetails()
 180            ///     .AddJsonBody("POST", "/users/", MyJsonContext.Default.CreateUserRequest, "body")
 181            ///     .AddHandler("POST", "/users/", (context, _) =&gt;
 182            ///     {
 183            ///         CreateUserRequest body = (CreateUserRequest) context.Parameters["body"]!;
 184            ///         return Task.FromResult(HttpResponseMessage.Json(HttpStatusCode.Created, body));
 185            ///     });
 186            /// </code>
 187            /// </example>
 188            /// <exception cref="ArgumentNullException">
 189            /// Thrown when <paramref name="routeScopeBuilder"/>, <paramref name="verbs"/>,
 190            /// <paramref name="pattern"/>, <paramref name="typeInfo"/>, or <paramref name="paramName"/> is
 191            /// <see langword="null"/>.
 192            /// </exception>
 193            /// <exception cref="ArgumentException">
 194            /// Thrown when an entry in <paramref name="verbs"/> is not supported or <paramref name="pattern"/> has
 195            /// invalid route-template syntax.
 196            /// </exception>
 197            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 198            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 199            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 200            public TBuilder AddJsonBody(IEnumerable<string> verbs, string pattern, JsonTypeInfo typeInfo, string paramNa
 201                routeScopeBuilder.AddHandler(verbs, pattern, CreateJsonBodyHandler(typeInfo, paramName));
 202
 203            /// <summary>
 204            /// Deserializes JSON request bodies into a route parameter for a single HTTP method.
 205            /// </summary>
 206            /// <param name="verb">The HTTP method that should require a JSON body.</param>
 207            /// <param name="pattern">
 208            /// The route pattern where the JSON-binding middleware should be inserted. Use <c>/</c> to apply it
 209            /// to the whole pipeline, or a narrower prefix/exact pattern to scope body binding to selected routes.
 210            /// </param>
 211            /// <param name="typeInfo">The metadata used to deserialize the request body.</param>
 212            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 213            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 214            /// <exception cref="ArgumentNullException">
 215            /// Thrown when <paramref name="routeScopeBuilder"/>, <paramref name="verb"/>,
 216            /// <paramref name="pattern"/>, <paramref name="typeInfo"/>, or <paramref name="paramName"/> is
 217            /// <see langword="null"/>.
 218            /// </exception>
 219            /// <exception cref="ArgumentException">Thrown when <paramref name="verb"/> is not supported or <paramref na
 220            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 221            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 222            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 223            /// <example>
 224            /// <code>
 225            /// builder.AddJsonBody("POST", "/users/", MyJsonContext.Default.CreateUserRequest, "body");
 226            /// </code>
 227            /// </example>
 228            public TBuilder AddJsonBody(string verb, string pattern, JsonTypeInfo typeInfo, string paramName) =>
 229                routeScopeBuilder.AddJsonBody([verb /*will be null checked*/], pattern, typeInfo, paramName);
 230
 231            /// <summary>
 232            /// Deserializes JSON request bodies into a route parameter for the selected HTTP methods.
 233            /// </summary>
 234            /// <param name="verbs">The HTTP methods that should require a JSON body.</param>
 235            /// <param name="typeInfo">The metadata used to deserialize the request body.</param>
 236            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 237            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 238            /// <remarks>
 239            /// This overload uses <see cref="RouteScopeBuilder.CurrentPrefix"/> as the route pattern, so the JSON-bindi
 240            /// middleware is bound to the whole current builder scope for the selected HTTP methods.
 241            /// </remarks>
 242            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name
 243            /// <exception cref="ArgumentException">Thrown when an entry in <paramref name="verbs"/> is not a supported 
 244            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 245            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 246            /// <example>
 247            /// <code>
 248            /// builder.AddJsonBody(["POST", "PUT"], MyJsonContext.Default.CreateUserRequest, "body");
 249            /// </code>
 250            /// </example>
 251            public TBuilder AddJsonBody(IEnumerable<string> verbs, JsonTypeInfo typeInfo, string paramName) =>
 252                routeScopeBuilder.AddJsonBody(verbs, RouteScopeBuilder.CurrentPrefix, typeInfo, paramName);
 253
 254            /// <summary>
 255            /// Deserializes JSON request bodies into a route parameter for <c>POST</c>, <c>PUT</c>, and <c>PATCH</c>.
 256            /// </summary>
 257            /// <param name="pattern">
 258            /// The route pattern where the JSON-binding middleware should be inserted. Use <c>/</c> to apply it
 259            /// to the whole pipeline, or a narrower prefix/exact pattern to scope body binding to selected routes.
 260            /// </param>
 261            /// <param name="typeInfo">The metadata used to deserialize the request body.</param>
 262            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 263            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 264            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name
 265            /// <exception cref="ArgumentException">Thrown when <paramref name="pattern"/> has invalid route-template sy
 266            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 267            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 268            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 269            /// <example>
 270            /// <code>
 271            /// builder.AddJsonBody("/users/", MyJsonContext.Default.CreateUserRequest, "body");
 272            /// </code>
 273            /// </example>
 274            public TBuilder AddJsonBody(string pattern, JsonTypeInfo typeInfo, string paramName) =>
 275                routeScopeBuilder.AddJsonBody(HttpVerb.HavingBody, pattern, typeInfo, paramName);
 276
 277            /// <summary>
 278            /// Deserializes JSON request bodies into a route parameter for <c>POST</c>, <c>PUT</c>, and <c>PATCH</c>.
 279            /// </summary>
 280            /// <param name="typeInfo">The metadata used to deserialize the request body.</param>
 281            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 282            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 283            /// <remarks>
 284            /// This overload uses <see cref="RouteScopeBuilder.CurrentPrefix"/> as the route pattern, so the JSON-bindi
 285            /// middleware is bound to the whole current builder scope for <c>POST</c>, <c>PUT</c>, and <c>PATCH</c>.
 286            /// </remarks>
 287            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name
 288            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 289            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 290            /// <example>
 291            /// <code>
 292            /// builder.AddJsonBody(MyJsonContext.Default.CreateUserRequest, "body");
 293            /// </code>
 294            /// </example>
 295            public TBuilder AddJsonBody(JsonTypeInfo typeInfo, string paramName) =>
 296                routeScopeBuilder.AddJsonBody(HttpVerb.HavingBody, RouteScopeBuilder.CurrentPrefix, typeInfo, paramName)
 297
 298            /// <summary>
 299            /// Deserializes JSON request bodies into a route parameter using runtime type metadata.
 300            /// </summary>
 301            /// <param name="verbs">The HTTP methods that should require a JSON body.</param>
 302            /// <param name="pattern">
 303            /// The route pattern where the JSON-binding middleware should be inserted. Use <c>/</c> to apply it
 304            /// to the whole pipeline, or a narrower prefix/exact pattern to scope body binding to selected routes.
 305            /// </param>
 306            /// <param name="type">The CLR type expected in the request body.</param>
 307            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 308            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 309            /// <exception cref="ArgumentNullException">
 310            /// Thrown when <paramref name="routeScopeBuilder"/>, <paramref name="verbs"/>,
 311            /// <paramref name="pattern"/>, <paramref name="type"/>, or <paramref name="paramName"/> is
 312            /// <see langword="null"/>.
 313            /// </exception>
 314            /// <exception cref="ArgumentException">
 315            /// Thrown when an entry in <paramref name="verbs"/> is not supported or <paramref name="pattern"/> has
 316            /// invalid route-template syntax.
 317            /// </exception>
 318            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 319            /// <exception cref="NotSupportedException">Thrown when JSON metadata cannot be resolved for <paramref name=
 320            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 321            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 322            /// <example>
 323            /// <code>
 324            /// builder.AddJsonBody(["POST", "PUT"], "/users/", typeof(CreateUserRequest), "body");
 325            /// </code>
 326            /// </example>
 327            public TBuilder AddJsonBody(IEnumerable<string> verbs, string pattern, Type type, string paramName)
 328            {
 329                Ensure.NotNull(type);
 330
 331                return routeScopeBuilder.AddJsonBody
 332                (
 333                    verbs,
 334                    pattern,
 335                    JsonSerializerOptions.Web.GetTypeInfo(type),
 336                    paramName
 337                );
 338            }
 339
 340            /// <summary>
 341            /// Deserializes JSON request bodies into a route parameter using runtime type metadata.
 342            /// </summary>
 343            /// <param name="verb">The HTTP method that should require a JSON body.</param>
 344            /// <param name="pattern">
 345            /// The route pattern where the JSON-binding middleware should be inserted. Use <c>/</c> to apply it
 346            /// to the whole pipeline, or a narrower prefix/exact pattern to scope body binding to selected routes.
 347            /// </param>
 348            /// <param name="type">The CLR type expected in the request body.</param>
 349            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 350            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 351            /// <exception cref="ArgumentNullException">
 352            /// Thrown when <paramref name="routeScopeBuilder"/>, <paramref name="verb"/>,
 353            /// <paramref name="pattern"/>, <paramref name="type"/>, or <paramref name="paramName"/> is
 354            /// <see langword="null"/>.
 355            /// </exception>
 356            /// <exception cref="ArgumentException">Thrown when <paramref name="verb"/> is not supported or <paramref na
 357            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 358            /// <exception cref="NotSupportedException">Thrown when JSON metadata cannot be resolved for <paramref name=
 359            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 360            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 361            /// <example>
 362            /// <code>
 363            /// builder.AddJsonBody("POST", "/users/", typeof(CreateUserRequest), "body");
 364            /// </code>
 365            /// </example>
 366            public TBuilder AddJsonBody(string verb, string pattern, Type type, string paramName) =>
 367                routeScopeBuilder.AddJsonBody([verb /*will be null checked*/], pattern, type, paramName);
 368
 369            /// <summary>
 370            /// Deserializes JSON request bodies into a route parameter using runtime type metadata.
 371            /// </summary>
 372            /// <param name="verbs">The HTTP methods that should require a JSON body.</param>
 373            /// <param name="type">The CLR type expected in the request body.</param>
 374            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 375            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 376            /// <remarks>
 377            /// This overload uses <see cref="RouteScopeBuilder.CurrentPrefix"/> as the route pattern, so the JSON-bindi
 378            /// middleware is bound to the whole current builder scope for the selected HTTP methods.
 379            /// </remarks>
 380            /// <exception cref="ArgumentNullException">
 381            /// Thrown when <paramref name="routeScopeBuilder"/>, <paramref name="verbs"/>,
 382            /// <paramref name="type"/>, or <paramref name="paramName"/> is <see langword="null"/>.
 383            /// </exception>
 384            /// <exception cref="ArgumentException">Thrown when an entry in <paramref name="verbs"/> is not a supported 
 385            /// <exception cref="NotSupportedException">Thrown when JSON metadata cannot be resolved for <paramref name=
 386            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 387            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 388            /// <example>
 389            /// <code>
 390            /// builder.AddJsonBody(["POST", "PUT"], typeof(CreateUserRequest), "body");
 391            /// </code>
 392            /// </example>
 393            public TBuilder AddJsonBody(IEnumerable<string> verbs, Type type, string paramName) =>
 394                routeScopeBuilder.AddJsonBody(verbs, RouteScopeBuilder.CurrentPrefix, type, paramName);
 395
 396            /// <summary>
 397            /// Deserializes JSON request bodies into a route parameter using runtime type metadata for <c>POST</c>, <c>
 398            /// </summary>
 399            /// <param name="pattern">
 400            /// The route pattern where the JSON-binding middleware should be inserted. Use <c>/</c> to apply it
 401            /// to the whole pipeline, or a narrower prefix/exact pattern to scope body binding to selected routes.
 402            /// </param>
 403            /// <param name="type">The CLR type expected in the request body.</param>
 404            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 405            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 406            /// <exception cref="ArgumentNullException">
 407            /// Thrown when <paramref name="routeScopeBuilder"/>, <paramref name="pattern"/>,
 408            /// <paramref name="type"/>, or <paramref name="paramName"/> is <see langword="null"/>.
 409            /// </exception>
 410            /// <exception cref="ArgumentException">Thrown when <paramref name="pattern"/> has invalid route-template sy
 411            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 412            /// <exception cref="NotSupportedException">Thrown when JSON metadata cannot be resolved for <paramref name=
 413            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 414            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 415            /// <example>
 416            /// <code>
 417            /// builder.AddJsonBody("/users/", typeof(CreateUserRequest), "body");
 418            /// </code>
 419            /// </example>
 420            public TBuilder AddJsonBody(string pattern, Type type, string paramName) =>
 421                routeScopeBuilder.AddJsonBody(HttpVerb.HavingBody, pattern, type, paramName);
 422
 423            /// <summary>
 424            /// Deserializes JSON request bodies into a route parameter using runtime type metadata for <c>POST</c>, <c>
 425            /// </summary>
 426            /// <param name="type">The CLR type expected in the request body.</param>
 427            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 428            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 429            /// <remarks>
 430            /// This overload uses <see cref="RouteScopeBuilder.CurrentPrefix"/> as the route pattern, so the JSON-bindi
 431            /// middleware is bound to the whole current builder scope for <c>POST</c>, <c>PUT</c>, and <c>PATCH</c>.
 432            /// </remarks>
 433            /// <exception cref="ArgumentNullException">
 434            /// Thrown when <paramref name="routeScopeBuilder"/>, <paramref name="type"/>, or
 435            /// <paramref name="paramName"/> is <see langword="null"/>.
 436            /// </exception>
 437            /// <exception cref="NotSupportedException">Thrown when JSON metadata cannot be resolved for <paramref name=
 438            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 439            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 440            /// <example>
 441            /// <code>
 442            /// builder.AddJsonBody(typeof(CreateUserRequest), "body");
 443            /// </code>
 444            /// </example>
 445            public TBuilder AddJsonBody(Type type, string paramName) =>
 446                routeScopeBuilder.AddJsonBody(HttpVerb.HavingBody, RouteScopeBuilder.CurrentPrefix, type, paramName);
 447
 448            /// <summary>
 449            /// Adds middleware that converts router exceptions into JSON <see cref="ErrorDetails"/> responses for all s
 450            /// </summary>
 451            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 452            /// <remarks>
 453            /// This overload uses <see cref="RouteScopeBuilder.CurrentPrefix"/> as the route pattern, so the error-deta
 454            /// middleware is bound to the whole current builder scope for all supported HTTP methods.
 455            /// </remarks>
 456            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/> is <see langwor
 457            /// <example>
 458            /// <code>
 459            /// builder.AddJsonErrorDetails();
 460            /// </code>
 461            /// </example>
 462            public TBuilder AddJsonErrorDetails() =>
 463                routeScopeBuilder.AddJsonErrorDetails(HttpVerb.Names, RouteScopeBuilder.CurrentPrefix, s_noopConfigure);
 464
 465            /// <summary>
 466            /// Adds middleware that converts router exceptions into JSON <see cref="ErrorDetails"/> responses for all s
 467            /// </summary>
 468            /// <param name="configure">Configures JSON error rendering and exception normalization for this middleware 
 469            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 470            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/> or <paramref na
 471            /// <example>
 472            /// <code>
 473            /// builder.AddJsonErrorDetails(options =&gt; options.Map&lt;NotSupportedException&gt;
 474            /// (
 475            ///     static ex =&gt; new HttpRequestException("Not supported", ex, HttpStatusCode.BadRequest)
 476            /// ));
 477            /// </code>
 478            /// </example>
 479            public TBuilder AddJsonErrorDetails(Action<JsonErrorDetailsOptions> configure) =>
 480                routeScopeBuilder.AddJsonErrorDetails(HttpVerb.Names, RouteScopeBuilder.CurrentPrefix, configure);
 481
 482            /// <summary>
 483            /// Adds middleware that converts router exceptions into JSON <see cref="ErrorDetails"/> responses for all s
 484            /// </summary>
 485            /// <param name="pattern">
 486            /// The route pattern where the error-detail middleware should be inserted. Use <c>/</c> to apply it to
 487            /// the whole pipeline, or a narrower prefix/exact pattern to scope JSON error responses to selected routes.
 488            /// </param>
 489            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 490            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/> or <paramref na
 491            /// <exception cref="ArgumentException">Thrown when <paramref name="pattern"/> has invalid route-template sy
 492            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 493            /// <example>
 494            /// <code>
 495            /// builder.AddJsonErrorDetails("/api/*");
 496            /// </code>
 497            /// </example>
 498            public TBuilder AddJsonErrorDetails(string pattern) =>
 499                routeScopeBuilder.AddJsonErrorDetails(HttpVerb.Names, pattern, s_noopConfigure);
 500
 501            /// <summary>
 502            /// Adds middleware that converts router exceptions into JSON <see cref="ErrorDetails"/> responses for all s
 503            /// </summary>
 504            /// <param name="pattern">
 505            /// The route pattern where the error-detail middleware should be inserted. Use <c>/</c> to apply it to
 506            /// the whole pipeline, or a narrower prefix/exact pattern to scope JSON error responses to selected routes.
 507            /// </param>
 508            /// <param name="configure">Configures JSON error rendering and exception normalization for this middleware 
 509            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 510            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name
 511            /// <exception cref="ArgumentException">Thrown when <paramref name="pattern"/> has invalid route-template sy
 512            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 513            /// <example>
 514            /// <code>
 515            /// builder.AddJsonErrorDetails("/api/*", options =&gt; options.PopulateErrorInfo = true);
 516            /// </code>
 517            /// </example>
 518            public TBuilder AddJsonErrorDetails(string pattern, Action<JsonErrorDetailsOptions> configure) =>
 519                routeScopeBuilder.AddJsonErrorDetails(HttpVerb.Names, pattern, configure);
 520
 521            /// <summary>
 522            /// Adds middleware that converts router exceptions into JSON <see cref="ErrorDetails"/> responses for a sin
 523            /// </summary>
 524            /// <param name="verb">The HTTP method that should use the error-detail middleware.</param>
 525            /// <param name="pattern">
 526            /// The route pattern where the error-detail middleware should be inserted. Use <c>/</c> to apply it to
 527            /// the whole pipeline, or a narrower prefix/exact pattern to scope JSON error responses to selected routes.
 528            /// </param>
 529            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 530            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name
 531            /// <exception cref="ArgumentException">Thrown when <paramref name="verb"/> is not supported or <paramref na
 532            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 533            /// <example>
 534            /// <code>
 535            /// builder.AddJsonErrorDetails("GET", "/api/*");
 536            /// </code>
 537            /// </example>
 538            public TBuilder AddJsonErrorDetails(string verb, string pattern) =>
 539                routeScopeBuilder.AddJsonErrorDetails([verb /*will be null checked*/], pattern, s_noopConfigure);
 540
 541            /// <summary>
 542            /// Adds middleware that converts router exceptions into JSON <see cref="ErrorDetails"/> responses for a sin
 543            /// </summary>
 544            /// <param name="verb">The HTTP method that should use the error-detail middleware.</param>
 545            /// <param name="pattern">
 546            /// The route pattern where the error-detail middleware should be inserted. Use <c>/</c> to apply it to
 547            /// the whole pipeline, or a narrower prefix/exact pattern to scope JSON error responses to selected routes.
 548            /// </param>
 549            /// <param name="configure">Configures JSON error rendering and exception normalization for this middleware 
 550            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 551            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name
 552            /// <exception cref="ArgumentException">Thrown when <paramref name="verb"/> is not supported or <paramref na
 553            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 554            /// <example>
 555            /// <code>
 556            /// builder.AddJsonErrorDetails("GET", "/api/*", options =&gt; options.PopulateErrorInfo = true);
 557            /// </code>
 558            /// </example>
 559            public TBuilder AddJsonErrorDetails(string verb, string pattern, Action<JsonErrorDetailsOptions> configure) 
 560                routeScopeBuilder.AddJsonErrorDetails([verb /*will be null checked*/], pattern, configure);
 561
 562            /// <summary>
 563            /// Adds middleware that converts router exceptions into JSON <see cref="ErrorDetails"/> responses for the s
 564            /// </summary>
 565            /// <param name="verbs">The HTTP methods that should use the error-detail middleware.</param>
 566            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 567            /// <remarks>
 568            /// This overload uses <see cref="RouteScopeBuilder.CurrentPrefix"/> as the route pattern, so the error-deta
 569            /// middleware is bound to the whole current builder scope for the selected HTTP methods.
 570            /// </remarks>
 571            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/> or <paramref na
 572            /// <exception cref="ArgumentException">Thrown when an entry in <paramref name="verbs"/> is not a supported 
 573            /// <example>
 574            /// <code>
 575            /// builder.AddJsonErrorDetails(["GET", "POST"]);
 576            /// </code>
 577            /// </example>
 578            public TBuilder AddJsonErrorDetails(IEnumerable<string> verbs) =>
 579                routeScopeBuilder.AddJsonErrorDetails(verbs, RouteScopeBuilder.CurrentPrefix, s_noopConfigure);
 580
 581            /// <summary>
 582            /// Adds middleware that converts router exceptions into JSON <see cref="ErrorDetails"/> responses for the s
 583            /// </summary>
 584            /// <param name="verbs">The HTTP methods that should use the error-detail middleware.</param>
 585            /// <param name="configure">Configures JSON error rendering and exception normalization for this middleware 
 586            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 587            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name
 588            /// <exception cref="ArgumentException">Thrown when an entry in <paramref name="verbs"/> is not a supported 
 589            /// <example>
 590            /// <code>
 591            /// builder.AddJsonErrorDetails(["GET", "POST"], options =&gt; options.PopulateErrorInfo = true);
 592            /// </code>
 593            /// </example>
 594            public TBuilder AddJsonErrorDetails(IEnumerable<string> verbs, Action<JsonErrorDetailsOptions> configure) =>
 595                routeScopeBuilder.AddJsonErrorDetails(verbs, RouteScopeBuilder.CurrentPrefix, configure);
 596
 597            /// <summary>
 598            /// Adds middleware that converts router exceptions into JSON <see cref="ErrorDetails"/> responses.
 599            /// </summary>
 600            /// <param name="verbs">The HTTP methods that should use the error-detail middleware.</param>
 601            /// <param name="pattern">
 602            /// The route pattern where the error-detail middleware should be inserted. Use <c>/</c> to apply it to
 603            /// the whole pipeline, or a narrower prefix/exact pattern to scope JSON error responses to selected routes.
 604            /// </param>
 605            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 606            /// <remarks>
 607            /// This helper wraps <see cref="HttpRequestException"/> values into JSON responses and also installs
 608            /// <see cref="NanoRouteExceptionExtensions.AddExceptionHandler{TBuilder}(TBuilder)"/> so unexpected
 609            /// exceptions are normalized before they reach the client. <see cref="OperationCanceledException"/> is
 610            /// not translated into JSON and continues to propagate to the caller unchanged. Use a callback overload
 611            /// to include developer diagnostics, replace the <see cref="ErrorDetails"/> serialization metadata, or
 612            /// customize exception normalization.
 613            /// </remarks>
 614            /// <example>
 615            /// <code>
 616            /// routerBuilder
 617            ///     .AddJsonErrorDetails()
 618            ///     .AddHandler("GET", "/items/{id:int}/", (context, _) =&gt;
 619            ///         throw new InvalidOperationException("Unexpected state"));
 620            /// </code>
 621            /// </example>
 622            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name
 623            /// <exception cref="ArgumentException">Thrown when an entry in <paramref name="verbs"/> is not supported or
 624            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 625            public TBuilder AddJsonErrorDetails(IEnumerable<string> verbs, string pattern) =>
 626                routeScopeBuilder.AddJsonErrorDetails(verbs, pattern, s_noopConfigure);
 627
 628            /// <summary>
 629            /// Adds middleware that converts router exceptions into JSON <see cref="ErrorDetails"/> responses.
 630            /// </summary>
 631            /// <param name="verbs">The HTTP methods that should use the error-detail middleware.</param>
 632            /// <param name="pattern">
 633            /// The route pattern where the error-detail middleware should be inserted. Use <c>/</c> to apply it to
 634            /// the whole pipeline, or a narrower prefix/exact pattern to scope JSON error responses to selected routes.
 635            /// </param>
 636            /// <param name="configure">Configures JSON error rendering and exception normalization for this middleware 
 637            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 638            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name
 639            /// <exception cref="ArgumentException">Thrown when an entry in <paramref name="verbs"/> is not supported or
 640            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 641            /// <example>
 642            /// <code>
 643            /// builder.AddJsonErrorDetails(["GET", "POST"], "/api/*", options =&gt;
 644            /// {
 645            ///     options.PopulateErrorInfo = true;
 646            ///     options.Map&lt;NotSupportedException&gt;
 647            ///     (
 648            ///         static ex =&gt; new HttpRequestException("Not supported", ex, HttpStatusCode.BadRequest)
 649            ///     );
 650            /// });
 651            /// </code>
 652            /// </example>
 653            public TBuilder AddJsonErrorDetails(IEnumerable<string> verbs, string pattern, Action<JsonErrorDetailsOption
 654            {
 655                Ensure.NotNull(configure);
 656
 657                JsonErrorDetailsOptions options = new();
 658                configure.Invoke(options);
 659
 660                return routeScopeBuilder.AddJsonErrorDetails(verbs, pattern, options);
 661            }
 662
 663            /// <summary>
 664            /// Adds middleware that converts router exceptions into JSON <see cref="ErrorDetails"/> responses.
 665            /// </summary>
 666            /// <param name="verbs">The HTTP methods that should use the error-detail middleware.</param>
 667            /// <param name="pattern">
 668            /// The route pattern where the error-detail middleware should be inserted. Use <c>/</c> to apply it to
 669            /// the whole pipeline, or a narrower prefix/exact pattern to scope JSON error responses to selected routes.
 670            /// </param>
 671            /// <param name="options">The JSON error rendering and exception-normalization options used by this middlewa
 672            /// <returns>The current <paramref name="routeScopeBuilder"/> instance.</returns>
 673            /// <exception cref="ArgumentNullException">Thrown when <paramref name="routeScopeBuilder"/>, <paramref name
 674            /// <exception cref="ArgumentException">Thrown when an entry in <paramref name="verbs"/> is not supported or
 675            /// <exception cref="InvalidOperationException">Thrown when <paramref name="pattern"/> uses unsupported rout
 676            /// <example>
 677            /// <code>
 678            /// JsonErrorDetailsOptions options = new()
 679            /// {
 680            ///     PopulateErrorInfo = true
 681            /// };
 682            ///
 683            /// options.Map&lt;NotSupportedException&gt;
 684            /// (
 685            ///     static ex =&gt; new HttpRequestException("Not supported", ex, HttpStatusCode.BadRequest)
 686            /// );
 687            ///
 688            /// builder.AddJsonErrorDetails(["GET", "POST"], "/api/*", options);
 689            /// </code>
 690            /// </example>
 691            public TBuilder AddJsonErrorDetails(IEnumerable<string> verbs, string pattern, JsonErrorDetailsOptions optio
 692            {
 693                Ensure.NotNull(routeScopeBuilder);
 694                Ensure.NotNull(verbs);
 695                Ensure.NotNull(pattern);
 696                Ensure.NotNull(options);
 697
 698                bool populateErrorInfo = options.PopulateErrorInfo;
 699
 700                JsonTypeInfo<ErrorDetails> errorDetailsTypeInfo = options.ErrorDetailsTypeInfo;
 701
 702                routeScopeBuilder
 703                    .AddHandler(verbs, pattern, async (RequestContext context, CallNextHandlerDelegate next) =>
 704                    {
 705                        try
 706                        {
 707                            return await next().ConfigureAwait(false);
 708                        }
 709                        catch (HttpRequestException ex)
 710                        {
 711                            ErrorDetails errorDetails = ex.GetErrorDetails(populateErrorInfo, context.Request.TraceId);
 712
 713                            return HttpResponseMessage.Json
 714                            (
 715                                errorDetails.Status,
 716                                errorDetails,
 717                                errorDetailsTypeInfo
 718                            );
 719                        }
 720                    })
 721                    .AddExceptionHandler(verbs, pattern, options);
 722
 723                return routeScopeBuilder;
 724            }
 725        }
 726
 727        extension(EndpointBuilder endpointBuilder)
 728        {
 729            /// <summary>
 730            /// Deserializes JSON request bodies into an endpoint parameter using source-generated or custom JSON metada
 731            /// </summary>
 732            /// <param name="typeInfo">The metadata used to deserialize the request body.</param>
 733            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 734            /// <returns>The current <paramref name="endpointBuilder"/> instance.</returns>
 735            /// <remarks>
 736            /// The JSON-binding middleware is registered for the endpoint's captured HTTP methods and route match
 737            /// kind. The deserialized body is written into <see cref="RequestContext.Parameters"/>, and an existing
 738            /// value with the same key is overwritten.
 739            /// </remarks>
 740            /// <exception cref="ArgumentNullException">Thrown when <paramref name="endpointBuilder"/>, <paramref name="
 741            /// <exception cref="ArgumentException">Thrown when the endpoint's captured HTTP method is not supported.</e
 742            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 743            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 744            /// <example>
 745            /// <code>
 746            /// endpoint.WithJsonBody(MyJsonContext.Default.CreateUserRequest, "body");
 747            /// </code>
 748            /// </example>
 749            public EndpointBuilder WithJsonBody(JsonTypeInfo typeInfo, string paramName)
 750            {
 751                Ensure.NotNull(endpointBuilder);
 752
 753                return endpointBuilder.WithHandler
 754                (
 755                    CreateJsonBodyHandler(typeInfo, paramName)
 756                );
 757            }
 758
 759            /// <summary>
 760            /// Deserializes JSON request bodies into an endpoint parameter using runtime type metadata.
 761            /// </summary>
 762            /// <param name="type">The CLR type expected in the request body.</param>
 763            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 764            /// <returns>The current <paramref name="endpointBuilder"/> instance.</returns>
 765            /// <exception cref="ArgumentNullException">Thrown when <paramref name="endpointBuilder"/>, <paramref name="
 766            /// <exception cref="ArgumentException">Thrown when the endpoint's captured HTTP method is not supported.</e
 767            /// <exception cref="NotSupportedException">Thrown when JSON metadata cannot be resolved for <paramref name=
 768            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 769            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 770            /// <example>
 771            /// <code>
 772            /// endpoint.WithJsonBody(typeof(CreateUserRequest), "body");
 773            /// </code>
 774            /// </example>
 775            public EndpointBuilder WithJsonBody(Type type, string paramName)
 776            {
 777                Ensure.NotNull(type);
 778
 779                return endpointBuilder.WithJsonBody
 780                (
 781                    JsonSerializerOptions.Web.GetTypeInfo(type),
 782                    paramName
 783                );
 784            }
 785
 786            /// <summary>
 787            /// Deserializes JSON request bodies into an endpoint parameter using runtime type metadata.
 788            /// </summary>
 789            /// <typeparam name="T">The CLR type expected in the request body.</typeparam>
 790            /// <param name="paramName">The parameter name under which the deserialized body will be stored.</param>
 791            /// <returns>The current <paramref name="endpointBuilder"/> instance.</returns>
 792            /// <exception cref="ArgumentNullException">Thrown when <paramref name="endpointBuilder"/> or <paramref name
 793            /// <exception cref="ArgumentException">Thrown when the endpoint's captured HTTP method is not supported.</e
 794            /// <exception cref="NotSupportedException">Thrown when JSON metadata cannot be resolved for <typeparamref n
 795            /// <exception cref="HttpRequestException">Thrown during request processing when the body is missing, the co
 796            /// <exception cref="OperationCanceledException">Thrown during request processing when the request cancellat
 797            /// <example>
 798            /// <code>
 799            /// endpoint.WithJsonBody&lt;CreateUserRequest&gt;("body");
 800            /// </code>
 801            /// </example>
 802            public EndpointBuilder WithJsonBody<T>(string paramName) => endpointBuilder.WithJsonBody(typeof(T), paramNam
 803        }
 804
 805        extension(HttpResponseMessage)
 806        {
 807            /// <summary>
 808            /// Creates a JSON response using the supplied type metadata.
 809            /// </summary>
 810            /// <param name="statusCode">The HTTP status code to assign to the response.</param>
 811            /// <param name="body">The value to serialize.</param>
 812            /// <param name="typeInfo">The metadata used to serialize <paramref name="body"/>.</param>
 813            /// <returns>A new <see cref="HttpResponseMessage"/> with JSON content.</returns>
 814            /// <exception cref="ArgumentNullException">Thrown when <paramref name="typeInfo"/> is <see langword="null"/
 815            /// <exception cref="InvalidOperationException">Thrown when the supplied JSON metadata is not compatible wit
 816            /// <exception cref="NotSupportedException">Thrown when the value cannot be serialized with the supplied JSO
 817            /// <example>
 818            /// <code>
 819            /// return HttpResponseMessage.Json(HttpStatusCode.Created, body, MyJsonContext.Default.CreateUserResponse);
 820            /// </code>
 821            /// </example>
 822            public static HttpResponseMessage Json(HttpStatusCode statusCode, object? body, JsonTypeInfo typeInfo)
 823            {
 824                Ensure.NotNull(typeInfo);
 825
 826                return new HttpResponseMessage(statusCode)
 827                {
 828                    Content = new StringContent
 829                    (
 830                        JsonSerializer.Serialize(body, typeInfo),
 831                        Encoding.UTF8,
 832                        JSON_MEDIA_TYPE
 833                    )
 834                };
 835            }
 836
 837            /// <summary>
 838            /// Creates a JSON response using the supplied type metadata.
 839            /// </summary>
 840            /// <param name="statusCode">The HTTP status code to assign to the response.</param>
 841            /// <param name="body">The value to serialize.</param>
 842            /// <param name="typeInfo">The metadata used to serialize <paramref name="body"/>.</param>
 843            /// <returns>A new <see cref="HttpResponseMessage"/> with JSON content.</returns>
 844            /// <exception cref="ArgumentNullException">Thrown when <paramref name="typeInfo"/> is <see langword="null"/
 845            /// <exception cref="InvalidOperationException">Thrown when the supplied JSON metadata is not compatible wit
 846            /// <exception cref="NotSupportedException">Thrown when the value cannot be serialized with the supplied JSO
 847            /// <example>
 848            /// <code>
 849            /// return HttpResponseMessage.Json(HttpStatusCode.OK, body, MyJsonContext.Default.CreateUserResponse);
 850            /// </code>
 851            /// </example>
 852            public static HttpResponseMessage Json<T>(HttpStatusCode statusCode, T? body, JsonTypeInfo<T> typeInfo)
 853            {
 854                Ensure.NotNull(typeInfo);
 855
 856                return Json(statusCode, (object?) body, typeInfo);
 857            }
 858
 859            /// <summary>
 860            /// Creates a JSON response using serializer <paramref name="options"/> to resolve metadata for <typeparamre
 861            /// </summary>
 862            /// <typeparam name="T">The type of the response body.</typeparam>
 863            /// <param name="statusCode">The HTTP status code to assign to the response.</param>
 864            /// <param name="body">The value to serialize.</param>
 865            /// <param name="options">The serializer options used to resolve metadata and serialization behavior.</param
 866            /// <returns>A new <see cref="HttpResponseMessage"/> with JSON content.</returns>
 867            /// <exception cref="ArgumentNullException">Thrown when <paramref name="options"/> is <see langword="null"/>
 868            /// <exception cref="InvalidOperationException">Thrown when JSON metadata cannot be resolved or is not compa
 869            /// <exception cref="NotSupportedException">Thrown when the value cannot be serialized with the resolved JSO
 870            /// <example>
 871            /// <code>
 872            /// return HttpResponseMessage.Json(HttpStatusCode.OK, body, JsonSerializerOptions.Web);
 873            /// </code>
 874            /// </example>
 875            public static HttpResponseMessage Json<T>(HttpStatusCode statusCode, T? body, JsonSerializerOptions options)
 876            {
 877                Ensure.NotNull(options);
 878
 879                if (options.TypeInfoResolver is null)
 880                    // do not change the original options
 881                    options = new JsonSerializerOptions(options)
 882                    {
 883                        TypeInfoResolver = new DefaultJsonTypeInfoResolver()
 884                    };
 885
 886                return Json(statusCode, body, options.GetTypeInfo(typeof(T)));
 887            }
 888
 889            /// <summary>
 890            /// Creates a JSON response using <see cref="JsonSerializerOptions.Web"/>.
 891            /// </summary>
 892            /// <typeparam name="T">The type of the response body.</typeparam>
 893            /// <param name="statusCode">The HTTP status code to assign to the response.</param>
 894            /// <param name="body">The value to serialize.</param>
 895            /// <returns>A new <see cref="HttpResponseMessage"/> with JSON content.</returns>
 896            /// <exception cref="InvalidOperationException">Thrown when JSON metadata cannot be resolved or is not compa
 897            /// <exception cref="NotSupportedException">Thrown when the value cannot be serialized with the resolved JSO
 898            /// <example>
 899            /// <code>
 900            /// return HttpResponseMessage.Json(HttpStatusCode.Created, body);
 901            /// </code>
 902            /// </example>
 903            public static HttpResponseMessage Json<T>(HttpStatusCode statusCode, T? body) => Json(statusCode, body, Json
 904
 905            /// <summary>
 906            /// Creates a JSON response with <see cref="HttpStatusCode.OK"/>. This method uses <see cref="JsonSerializer
 907            /// </summary>
 908            /// <typeparam name="T">The type of the response body.</typeparam>
 909            /// <param name="body">The value to serialize.</param>
 910            /// <returns>A new <see cref="HttpResponseMessage"/> with JSON content.</returns>
 911            /// <exception cref="InvalidOperationException">Thrown when JSON metadata cannot be resolved or is not compa
 912            /// <exception cref="NotSupportedException">Thrown when the value cannot be serialized with the resolved JSO
 913            /// <example>
 914            /// <code>
 915            /// return HttpResponseMessage.Json(body);
 916            /// </code>
 917            /// </example>
 918            public static HttpResponseMessage Json<T>(T? body) => Json(HttpStatusCode.OK, body);
 919        }
 920
 921        extension(ErrorDetails)
 922        {
 923            /// <summary>
 924            /// Provides the default JSON serialization meta-data.
 925            /// </summary>
 926            /// <example>
 927            /// <code>
 928            /// JsonTypeInfo&lt;ErrorDetails&gt; typeInfo = ErrorDetails.JsonTypeInfo;
 929            /// </code>
 930            /// </example>
 931            public static JsonTypeInfo<ErrorDetails> JsonTypeInfo => JsonContext.Default.ErrorDetails;
 932        }
 933    }
 934}