using System.Text; using System.Text.Json.Nodes; using Connected.Interop; using Connected.Net; using Microsoft.AspNetCore.Http; namespace Connected.Rest; internal class JsonFormatter : ApiFormatter { public const string ContentType = "application/json"; protected override async Task OnParseArguments() { return await Context.Request.Deserialize(); } protected override async Task OnRenderError(int statusCode, string message) { Context.Response.ContentType = ContentType; Context.Response.StatusCode = statusCode; if (!string.IsNullOrWhiteSpace(message)) { var buffer = Encoding.UTF8.GetBytes(await Serializer.Serialize(new { Message = message })); Context.Response.ContentLength = buffer.Length; await Context.Response.Body.WriteAsync(buffer); } await Context.Response.CompleteAsync(); } protected override async Task OnRenderResult(object content) { if (!Context.Response.HasStarted) { var buffer = content is null ? Array.Empty() : Encoding.UTF8.GetBytes(await Serializer.Serialize(content)); Context.Response.Clear(); Context.Response.ContentLength = buffer.Length; Context.Response.ContentType = ContentType; Context.Response.StatusCode = StatusCodes.Status200OK; await Context.Response.Body.WriteAsync(buffer); } await Context.Response.CompleteAsync(); } }