Beispiel #1
0
        public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
            if (encoding == null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }

            var request = context.HttpContext.Request;
            var buffer  = new ResizableMemory <byte>(1024 * 4);

            try
            {
                var read = await request.Body.ReadAsync(buffer.RequestMemory(1024 * 4));

                while (read > 0)
                {
                    buffer.Advance(read);
                    read = await request.Body.ReadAsync(buffer.RequestMemory(1024 * 4));
                }

                if (encoding == Encoding.UTF8)
                {
                    var obj = _serializer.ReadUtf8(context.ModelType, buffer.AsReadOnlySpan());
                    return(InputFormatterResult.Success(obj));
                }
                else if (encoding == Encoding.Unicode)
                {
                    var obj = _serializer.ReadUtf16(context.ModelType, buffer.AsReadOnlySpan());
                    return(InputFormatterResult.Success(obj));
                }
                else
                {
                    throw new ArgumentOutOfRangeException(nameof(encoding));
                }
            }
            catch (SerializationException)
            {
                return(InputFormatterResult.Failure());
            }
            catch (Exception ex)
            {
                throw new InputFormatterException($"Failed to deserialize {context.ModelType}", ex);
            }
            finally { buffer.Return(); }
        }