|
1 | 1 | using System;
|
2 | 2 | using System.Diagnostics.CodeAnalysis;
|
| 3 | +using System.Net.Http.Headers; |
3 | 4 | using System.Text;
|
4 | 5 | using System.Threading.Tasks;
|
5 | 6 | using WebApiClientCore.HttpContents;
|
@@ -36,9 +37,29 @@ public string CharSet
|
36 | 37 | [UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.", Justification = "<Pending>")]
|
37 | 38 | protected override Task SetHttpContentAsync(ApiParameterContext context)
|
38 | 39 | {
|
39 |
| - var options = context.HttpContext.HttpApiOptions.JsonSerializeOptions; |
40 |
| - context.HttpContext.RequestMessage.Content = new JsonContent(context.ParameterValue, options, this.encoding); |
| 40 | + context.HttpContext.RequestMessage.Content = this.CreateContent(context); |
41 | 41 | return Task.CompletedTask;
|
42 | 42 | }
|
| 43 | + |
| 44 | + [RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")] |
| 45 | + [RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")] |
| 46 | +#if NET5_0_OR_GREATER |
| 47 | + private System.Net.Http.Json.JsonContent CreateContent(ApiParameterContext context) |
| 48 | + { |
| 49 | + var value = context.ParameterValue; |
| 50 | + var options = context.HttpContext.HttpApiOptions.JsonSerializeOptions; |
| 51 | + var valueType = value == null ? context.Parameter.ParameterType : value.GetType(); |
| 52 | + var mediaType = Encoding.UTF8.Equals(this.encoding) ? defaultMediaType : new MediaTypeHeaderValue(JsonContent.MediaType) { CharSet = this.CharSet }; |
| 53 | + return System.Net.Http.Json.JsonContent.Create(value, valueType, mediaType, options); |
| 54 | + } |
| 55 | + private static readonly MediaTypeHeaderValue defaultMediaType = new(JsonContent.MediaType); |
| 56 | +#else |
| 57 | + private JsonContent CreateContent(ApiParameterContext context) |
| 58 | + { |
| 59 | + var value = context.ParameterValue; |
| 60 | + var options = context.HttpContext.HttpApiOptions.JsonSerializeOptions; |
| 61 | + return new JsonContent(value, options, this.encoding); |
| 62 | + } |
| 63 | +#endif |
43 | 64 | }
|
44 | 65 | }
|
0 commit comments