| | | 1 | | using System.Net.Mime; |
| | | 2 | | using System.Text; |
| | | 3 | | using System.Text.Json; |
| | | 4 | | |
| | | 5 | | namespace ArturRios.Util.Http; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Provides HTTP-related extension helpers for serializing objects to HTTP content. |
| | | 9 | | /// </summary> |
| | | 10 | | /// <remarks> |
| | | 11 | | /// The extension is declared on a generic value rather than on <see cref="object"/>. Extending |
| | | 12 | | /// <see cref="object"/> would attach <c>ToJsonStringContent</c> to every type in every file that imports |
| | | 13 | | /// this namespace, including <see cref="int"/> and <see cref="string"/>. |
| | | 14 | | /// </remarks> |
| | | 15 | | public static class HttpExtensions |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Adds JSON serialization helpers for HTTP requests. |
| | | 19 | | /// </summary> |
| | | 20 | | /// <param name="value">The payload to serialize.</param> |
| | | 21 | | /// <typeparam name="TPayload">The payload type, used to drive serialization.</typeparam> |
| | | 22 | | extension<TPayload>(TPayload value) |
| | | 23 | | { |
| | | 24 | | /// <summary> |
| | | 25 | | /// Serializes the value to JSON and wraps it in a <see cref="StringContent"/> |
| | | 26 | | /// with UTF-8 encoding and <see cref="MediaTypeNames.Application.Json"/> media type. |
| | | 27 | | /// </summary> |
| | | 28 | | /// <returns> |
| | | 29 | | /// A <see cref="StringContent"/> instance containing the JSON representation of the value. |
| | | 30 | | /// </returns> |
| | | 31 | | public StringContent ToJsonStringContent() |
| | | 32 | | { |
| | 12 | 33 | | var json = JsonSerializer.Serialize(value, JsonDefaults.Options); |
| | | 34 | | |
| | 12 | 35 | | return new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json); |
| | | 36 | | } |
| | | 37 | | } |
| | | 38 | | } |