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/FormFormatter.cs

76 lines
1.9 KiB

using System.Reflection;
using System.Text;
using System.Text.Json.Nodes;
using Connected.Interop;
using Connected.Net;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.WebUtilities;
namespace Connected.Rest;
internal class FormFormatter : ApiFormatter
{
public const string ContentType = "application/x-www-form-urlencoded";
protected override async Task<JsonNode?> OnParseArguments()
{
using var reader = new StreamReader(Context.Request.Body, Encoding.UTF8);
var body = await reader.ReadToEndAsync();
var qs = QueryHelpers.ParseNullableQuery(body);
var result = new JsonObject();
foreach (var q in qs)
result.Add(q.Key, JsonValue.Create(q.Value));
Context.SetRequestArguments(result);
return result;
}
protected override async Task OnRenderResult(object content)
{
if (Context.Response.HasStarted)
{
var qs = new QueryString();
if (content is not null)
{
foreach (var property in content.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (!property.PropertyType.IsTypePrimitive())
continue;
qs.Add(property.Name.ToCamelCase(), property.GetValue(content) as string);
}
}
var buffer = Encoding.UTF8.GetBytes(qs.ToUriComponent());
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();
}
protected override async Task OnRenderError(int statusCode, string message)
{
Context.Response.ContentType = ContentType;
Context.Response.StatusCode = statusCode;
var qs = new QueryString();
qs.Add("message", message);
var buffer = Encoding.UTF8.GetBytes(qs.ToUriComponent());
Context.Response.ContentLength = buffer.Length;
await Context.Response.Body.WriteAsync(buffer);
await Context.Response.CompleteAsync();
}
}