using System; using System.Threading.Tasks; namespace EmbedIO.WebApi { /// /// 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 JsonDataAttribute : Attribute, IRequestDataAttribute { /// public async Task GetRequestDataAsync(WebApiController controller, Type type, string parameterName) { string body; using (var reader = controller.HttpContext.OpenRequestText()) { body = await reader.ReadToEndAsync().ConfigureAwait(false); } try { return Swan.Formatters.Json.Deserialize(body, type); } catch (FormatException) { throw HttpException.BadRequest($"Expected request body to be deserializable to {type.FullName}."); } } } }