aboutsummaryrefslogtreecommitdiff
path: root/docker/crupest-api/CrupestApi/CrupestApi.Commons/Json.cs
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2022-12-02 11:04:34 +0800
committercrupest <crupest@outlook.com>2022-12-02 13:35:35 +0800
commit879fb614c6853ab3bb83155c82722afb2933fc60 (patch)
tree2f80b57945408b8af83556a4efe5a92dea98e025 /docker/crupest-api/CrupestApi/CrupestApi.Commons/Json.cs
parent31416d8e047e4209f797881fd24e0e77256f3da1 (diff)
downloadcrupest-879fb614c6853ab3bb83155c82722afb2933fc60.tar.gz
crupest-879fb614c6853ab3bb83155c82722afb2933fc60.tar.bz2
crupest-879fb614c6853ab3bb83155c82722afb2933fc60.zip
...
Diffstat (limited to 'docker/crupest-api/CrupestApi/CrupestApi.Commons/Json.cs')
-rw-r--r--docker/crupest-api/CrupestApi/CrupestApi.Commons/Json.cs40
1 files changed, 40 insertions, 0 deletions
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<JsonSerializerOptions>();
+ services.Configure<JsonSerializerOptions>(config =>
+ {
+ config.AllowTrailingCommas = true;
+ config.PropertyNameCaseInsensitive = true;
+ config.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
+ });
+
+ return services;
+ }
+
+
+ public static async Task WriteJsonAsync<T>(this HttpResponse response, T bodyObject, int statusCode = 200, HttpResponseAction? beforeWriteBody = null, CancellationToken cancellationToken = default)
+ {
+ var jsonOptions = response.HttpContext.RequestServices.GetRequiredService<JsonSerializerOptions>();
+ byte[] json = JsonSerializer.SerializeToUtf8Bytes<T>(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);
+ }
+}