You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Connected.Framework/Connected.Rest/Api/JsonFormatter.cs

55 lines
1.3 KiB

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<JsonNode?> 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<byte>() : 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();
}
}