|
| 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 Microsoft.AspNetCore.Http.Features; |
| 6 | +using Microsoft.Extensions.Primitives; |
| 7 | + |
| 8 | +namespace Microsoft.AspNetCore.Http |
| 9 | +{ |
| 10 | + public static class ResponseTrailerExtensions |
| 11 | + { |
| 12 | + private const string Trailer = "Trailer"; |
| 13 | + |
| 14 | + /// <summary> |
| 15 | + /// Adds the given trailer name to the 'Trailer' response header. This must happen before the response headers are sent. |
| 16 | + /// </summary> |
| 17 | + /// <param name="response"></param> |
| 18 | + /// <param name="trailerName"></param> |
| 19 | + public static void DeclareTrailer(this HttpResponse response, string trailerName) |
| 20 | + { |
| 21 | + response.Headers.AppendCommaSeparatedValues(Trailer, trailerName); |
| 22 | + } |
| 23 | + |
| 24 | + /// <summary> |
| 25 | + /// Indicates if the server supports sending trailer headers for this response. |
| 26 | + /// </summary> |
| 27 | + /// <param name="response"></param> |
| 28 | + /// <returns></returns> |
| 29 | + public static bool SupportsTrailers(this HttpResponse response) |
| 30 | + { |
| 31 | + var feature = response.HttpContext.Features.Get<IHttpResponseTrailersFeature>(); |
| 32 | + return feature?.Trailers != null && !feature.Trailers.IsReadOnly; |
| 33 | + } |
| 34 | + |
| 35 | + /// <summary> |
| 36 | + /// Adds the given trailer header to the trailers collection to be sent at the end of the response body. |
| 37 | + /// Check <see cref="SupportsTrailers" /> or an InvalidOperationException may be thrown. |
| 38 | + /// </summary> |
| 39 | + /// <param name="response"></param> |
| 40 | + /// <param name="trailerName"></param> |
| 41 | + /// <param name="trailerValues"></param> |
| 42 | + public static void AppendTrailer(this HttpResponse response, string trailerName, StringValues trailerValues) |
| 43 | + { |
| 44 | + var feature = response.HttpContext.Features.Get<IHttpResponseTrailersFeature>(); |
| 45 | + if (feature?.Trailers == null || feature.Trailers.IsReadOnly) |
| 46 | + { |
| 47 | + throw new InvalidOperationException("Trailers are not supported for this response."); |
| 48 | + } |
| 49 | + |
| 50 | + feature.Trailers.Append(trailerName, trailerValues); |
| 51 | + } |
| 52 | + } |
| 53 | +} |
0 commit comments