From 300842e81a99db6da103f146d33eb47f43efc683 Mon Sep 17 00:00:00 2001 From: crupest Date: Fri, 2 Dec 2022 11:04:34 +0800 Subject: ... --- .../CrupestApi/CrupestApi.Commons/Json.cs | 40 ++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 docker/crupest-api/CrupestApi/CrupestApi.Commons/Json.cs (limited to 'docker/crupest-api/CrupestApi/CrupestApi.Commons/Json.cs') diff --git a/docker/crupest-api/CrupestApi/CrupestApi.Commons/Json.cs b/docker/crupest-api/CrupestApi/CrupestApi.Commons/Json.cs new file mode 100644 index 0000000..0ec3ff0 --- /dev/null +++ b/docker/crupest-api/CrupestApi/CrupestApi.Commons/Json.cs @@ -0,0 +1,40 @@ +using System.Text; +using System.Text.Json; + +namespace CrupestApi.Commons; + + +public static class CrupestApiJsonExtensions +{ + public static IServiceCollection AddJsonOptions(this IServiceCollection services) + { + services.AddOptions(); + services.Configure(config => + { + config.AllowTrailingCommas = true; + config.PropertyNameCaseInsensitive = true; + config.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + }); + + return services; + } + + + public static async Task WriteJsonAsync(this HttpResponse response, T bodyObject, int statusCode = 200, HttpResponseAction? beforeWriteBody = null, CancellationToken cancellationToken = default) + { + var jsonOptions = response.HttpContext.RequestServices.GetRequiredService(); + byte[] json = JsonSerializer.SerializeToUtf8Bytes(bodyObject, jsonOptions); + + var byteCount = json.Length; + response.StatusCode = statusCode; + response.Headers.ContentType = "application/json; charset=utf-8"; + response.Headers.ContentLength = byteCount; + + if (beforeWriteBody is not null) + { + await beforeWriteBody(response); + } + + await response.Body.WriteAsync(json, cancellationToken); + } +} -- cgit v1.2.3