Exemplo n.º 1
0
        public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context,
                                                                               Encoding encoding)
        {
            if (context == null)
            {
                throw new ArgumentException("{context} is null", nameof(context));
            }

            await using var requestStream = _recyclableMemoryStreamManager.GetStream();
            await context.HttpContext.Request.Body.CopyToAsync(requestStream);

            try
            {
                requestStream.Seek(0, SeekOrigin.Begin);

                const int readChunkBufferLength = 4096;
                await using var textWriter = new StringWriter();
                using var reader           = new StreamReader(requestStream);

                var readChunk = new char[readChunkBufferLength];
                int readChunkLength;

                do
                {
                    readChunkLength = await reader.ReadBlockAsync(readChunk, 0, readChunkBufferLength);

                    await textWriter.WriteAsync(readChunk, 0, readChunkLength);
                } while (readChunkLength > 0);

                var result = textWriter.ToString();
                if (!string.IsNullOrEmpty(result))
                {
                    var jsonParser = new FhirJsonParser();
                    var resource   = jsonParser.ParseAsync(result);

                    return(await InputFormatterResult.SuccessAsync(resource));
                }
            }
            catch
            {
                return(await InputFormatterResult.FailureAsync());
            }

            return(null);
        }