using System.Text.Json; using Microsoft.Extensions.Options; namespace CrupestApi.Commons; public static class CrupestApiJsonExtensions { public static object? CheckJsonValueNotArrayOrObject(this JsonElement value) { if (value.ValueKind == JsonValueKind.Null && value.ValueKind == JsonValueKind.Undefined) { return null; } else if (value.ValueKind == JsonValueKind.True) { return true; } else if (value.ValueKind == JsonValueKind.False) { return false; } else if (value.ValueKind == JsonValueKind.Number) { return value.GetDouble(); } else if (value.ValueKind == JsonValueKind.String) { return value.GetString(); } else { throw new Exception("Only value not array or object is allowed."); } } 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.Value); var byteCount = json.Length; response.StatusCode = statusCode; response.Headers.ContentType = "application/json; charset=utf-8"; response.Headers.ContentLength = byteCount; if (beforeWriteBody is not null) { beforeWriteBody(response); } await response.Body.WriteAsync(json, cancellationToken); } public static async Task WriteMessageAsync(this HttpResponse response, string message, int statusCode = 400, HttpResponseAction? beforeWriteBody = null, CancellationToken cancellationToken = default) { await response.WriteJsonAsync(new ErrorBody(message), statusCode: statusCode, beforeWriteBody, cancellationToken); } public static Task ResponseJsonAsync(this HttpContext context, T bodyObject, int statusCode = 200, HttpResponseAction? beforeWriteBody = null, CancellationToken cancellationToken = default) { return context.Response.WriteJsonAsync(bodyObject, statusCode, beforeWriteBody, cancellationToken); } public static Task ResponseMessageAsync(this HttpContext context, string message, int statusCode = 400, HttpResponseAction? beforeWriteBody = null, CancellationToken cancellationToken = default) { return context.Response.WriteMessageAsync(message, statusCode, beforeWriteBody, cancellationToken); } }