using System.Text.Json; using EmbedIO; using EmbedIO.WebApi; namespace TorchRemote.Plugin.Utils; /// /// Specifies that a parameter of a controller method will receive /// an object obtained by deserializing the request body as JSON. /// The received object will be /// only if the deserialized object is null. /// If the request body is not valid JSON, /// or if it cannot be deserialized to the type of the parameter, /// a 400 Bad Request response will be sent to the client. /// This class cannot be inherited. /// /// /// [AttributeUsage(AttributeTargets.Parameter)] public class JsonBodyAttribute : Attribute, IRequestDataAttribute { /// public async Task GetRequestDataAsync(WebApiController controller, Type type, string parameterName) { try { using var stream = controller.HttpContext.OpenRequestStream(); return await JsonSerializer.DeserializeAsync(stream, type, Statics.SerializerOptions); } catch (JsonException) { throw HttpException.BadRequest($"Expected request body to be deserializable to {type.FullName}."); } } }