public async Task FromJsonStream(IGraphQLTextSerializer serializer) { var test = $"{{\"query\":\"hello\",\"variables\":{ExampleJson}}}"; var testData = new MemoryStream(Encoding.UTF8.GetBytes(test)); var actual = await serializer.ReadAsync <TestClass1>(testData).ConfigureAwait(false); actual.Query.ShouldBe("hello"); Verify(actual.Variables); // verify that the stream has not been disposed testData.ReadByte().ShouldBe(-1); testData.Dispose(); Should.Throw <ObjectDisposedException>(() => testData.ReadByte()); }
public virtual async Task InvokeAsync(HttpContext context, RequestDelegate next) { if (context.WebSockets.IsWebSocketRequest) { await next(context); return; } // Handle requests as per recommendation at http://graphql.org/learn/serving-over-http/ // Inspiration: https://github.com/graphql/express-graphql/blob/master/src/index.js var httpRequest = context.Request; var httpResponse = context.Response; var cancellationToken = GetCancellationToken(context); // GraphQL HTTP only supports GET and POST methods bool isGet = HttpMethods.IsGet(httpRequest.Method); bool isPost = HttpMethods.IsPost(httpRequest.Method); if (!isGet && !isPost) { httpResponse.Headers["Allow"] = "GET, POST"; await HandleInvalidHttpMethodErrorAsync(context); return; } // Parse POST body GraphQLRequest bodyGQLRequest = null; IList <GraphQLRequest> bodyGQLBatchRequest = null; if (isPost) { if (!MediaTypeHeaderValue.TryParse(httpRequest.ContentType, out var mediaTypeHeader)) { await HandleContentTypeCouldNotBeParsedErrorAsync(context); return; } switch (mediaTypeHeader.MediaType) { case MediaType.JSON: IList <GraphQLRequest> deserializationResult; try { #if NET5_0_OR_GREATER if (!TryGetEncoding(mediaTypeHeader.CharSet, out var sourceEncoding)) { await HandleContentTypeCouldNotBeParsedErrorAsync(context); return; } // Wrap content stream into a transcoding stream that buffers the data transcoded from the sourceEncoding to utf-8. if (sourceEncoding != null && sourceEncoding != System.Text.Encoding.UTF8) { using var tempStream = System.Text.Encoding.CreateTranscodingStream(httpRequest.Body, innerStreamEncoding: sourceEncoding, outerStreamEncoding: System.Text.Encoding.UTF8, leaveOpen: true); deserializationResult = await _serializer.ReadAsync <IList <GraphQLRequest> >(tempStream, cancellationToken); } else { deserializationResult = await _serializer.ReadAsync <IList <GraphQLRequest> >(httpRequest.Body, cancellationToken); } #else deserializationResult = await _serializer.ReadAsync <IList <GraphQLRequest> >(httpRequest.Body, cancellationToken); #endif } catch (Exception ex) { if (!await HandleDeserializationErrorAsync(context, ex)) { throw; } return; } // https://github.com/graphql-dotnet/server/issues/751 if (deserializationResult is GraphQLRequest[] array && array.Length == 1) { bodyGQLRequest = deserializationResult[0]; } else { bodyGQLBatchRequest = deserializationResult; } break;