Пример #1
0
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
        {
            var response = context.HttpContext.Response;
            //var selectedEncoding = context.ContentType.Encoding == null ? Encoding.UTF8 : context.ContentType.Encoding;
            var selectedEncoding = Encoding.UTF8;

            var value = context.Object;

            if (value is IEdmModel || context.HttpContext.ODataProperties().Model == null)
            {
                using (var delegatingStream = new NonDisposableStream(response.Body))
                    using (var writer = new StreamWriter(delegatingStream, selectedEncoding, 1024, leaveOpen: true))
                    {
                        if (value is IEdmModel)
                        {
                            WriteMetadata(writer, (IEdmModel)value);
                        }

                        using (var jsonWriter = CreateJsonWriter(writer))
                        {
                            var jsonSerializer = CreateJsonSerializer();
                            jsonSerializer.Serialize(jsonWriter, value);
                        }
                    }
            }
            else
            {
                using (var delegatingStream = new NonDisposableStream(response.Body))
                {
                    await WriteObjectAsync(delegatingStream, context);
                }
            }
        }
        /// <inheritdoc />
        public override Task WriteResponseBodyAsync([NotNull] OutputFormatterContext context)
        {
            var tempWriterSettings = WriterSettings.Clone();

            tempWriterSettings.Encoding = context.SelectedEncoding;

            var innerStream = context.ActionContext.HttpContext.Response.Body;

            using (var outputStream = new NonDisposableStream(innerStream))
                using (var xmlWriter = CreateXmlWriter(outputStream, tempWriterSettings))
                {
                    var obj         = context.Object;
                    var runtimeType = obj?.GetType();

                    var resolvedType = ResolveType(context.DeclaredType, runtimeType);

                    var wrappingType = GetSerializableType(resolvedType);

                    // Wrap the object only if there is a wrapping type.
                    if (wrappingType != null && wrappingType != resolvedType)
                    {
                        var wrapperProvider = WrapperProviderFactories.GetWrapperProvider(
                            new WrapperProviderContext(
                                declaredType: resolvedType,
                                isSerialization: true));

                        obj = wrapperProvider.Wrap(obj);
                    }

                    var dataContractSerializer = GetCachedSerializer(wrappingType);
                    dataContractSerializer.WriteObject(xmlWriter, obj);
                }

            return(Task.FromResult(true));
        }
Пример #3
0
    public void InnerStreamIsNotFlushedOnDispose()
    {
        var stream = FlushReportingStream.GetThrowingStream();
        var nonDisposableStream = new NonDisposableStream(stream);

        // Act & Assert
        nonDisposableStream.Dispose();
    }
Пример #4
0
    public async Task InnerStreamIsNotFlushedOnFlushAsync()
    {
        // Arrange
        var stream = FlushReportingStream.GetThrowingStream();

        var nonDisposableStream = new NonDisposableStream(stream);

        // Act & Assert
        await nonDisposableStream.FlushAsync();
    }
Пример #5
0
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            var response = context.HttpContext.Response;

            //var selectedEncoding = context.ContentType.Encoding == null ? Encoding.UTF8 : context.ContentType.Encoding;
            //var selectedEncoding = Encoding.UTF8;

            var value = context.Object;

            if (value is IEdmModel || context.HttpContext.ODataFeature().Model == null)
            {
                using (var delegatingStream = new NonDisposableStream(response.Body))
                    using (var writer = new StreamWriter(delegatingStream, selectedEncoding, 1024, leaveOpen: true))
                    {
                        if (value is IEdmModel)
                        {
                            WriteMetadata(writer, (IEdmModel)value);
                        }
                        else
                        {
                            using (var jsonWriter = CreateJsonWriter(writer))
                            {
                                var jsonSerializer = CreateJsonSerializer();
                                jsonSerializer.Serialize(jsonWriter, value);
                            }
                        }
                    }
            }
            else
            {
                //IODataResponseMessageAsync response2 =  new ODataAsynchronousResponseMessage(response, response.StatusCode, response.Headers);

                //using (ODataMessageReader reader = new ODataMessageReader(response))
                //{
                //}
                //using (var ms = new MemoryStream())
                //{
                //    await WriteObjectAsync(ms, context);
                //    var content = Encoding.UTF8.GetString(ms.ToArray());
                //    if (context.Object == null || context.Object.GetType().GetTypeInfo().IsValueType)
                //    {
                //        await response.WriteAsync(content); // + "                                    ");
                //    }
                //    else
                //    {
                //        await response.WriteAsync(content);// + "                                    ");
                //    }
                //}
                using (var delegatingStream = new NonDisposableStream(response.Body))
                {
                    await WriteObjectAsync(delegatingStream, context);
                }
            }
        }
Пример #6
0
    public void InnerStreamIsOpenOnClose()
    {
        // Arrange
        var innerStream         = new MemoryStream();
        var nonDisposableStream = new NonDisposableStream(innerStream);

        // Act
        nonDisposableStream.Close();

        // Assert
        Assert.True(innerStream.CanRead);
    }
Пример #7
0
        public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
        {
            var response = context.HttpContext.Response;

            using (var delegatingStream = new NonDisposableStream(response.Body))
                using (var writer = new StreamWriter(delegatingStream, selectedEncoding, 1024, leaveOpen: true))
                {
                    WriteObject(writer, context.Object);
                }

            return(Task.FromResult(true));
        }
Пример #8
0
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context,
                                                          Encoding selectedEncoding)
        {
            if (context == null)
            {
                return;
            }


            var response = context.HttpContext.Response;

            using (var delegatingStream = new NonDisposableStream(response.Body))
                using (var streamWriter = new StreamWriter(delegatingStream, selectedEncoding, 1024, true))
                {
                    Serialize(context.ObjectType, context.Object as Resource, streamWriter, selectedEncoding);
                    await streamWriter.FlushAsync();
                }
        }
Пример #9
0
        public override async Task WriteResponseBodyAsync(OutputFormatterContext context)
        {
            var contact = (Contact)context.Object;

            var builder = new StringBuilder();

            builder.AppendLine("BEGIN:VCARD");
            builder.AppendFormat("FN:{0}", contact.Name);
            builder.AppendLine();
            builder.AppendLine("END:VCARD");

            var responseStream = new NonDisposableStream(context.ActionContext.HttpContext.Response.Body);

            using (var writer = new StreamWriter(responseStream, context.SelectedEncoding, bufferSize: 1024))
            {
                await writer.WriteAsync(builder.ToString());
            }
        }
        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;

            if (!request.Body.CanSeek)
            {
                request.EnableRewind();
            }

            //  XML serializer does synchronous reads. This loads everything
            //  into the buffer without blocking
            await request.Body.DrainAsync(CancellationToken.None);

            request.Body.Seek(0L, SeekOrigin.Begin);

            SoapV11Envelope soapEnvelope;

            using (var stream = new NonDisposableStream(request.Body))
                using (var reader = new XmlTextReader(stream))
                {
                    soapEnvelope = (SoapV11Envelope)EnvelopeSerializer.Deserialize(reader);
                }

            if (context.ModelType == typeof(SoapV11Envelope))
            {
                return(InputFormatterResult.Success(soapEnvelope));
            }

            using (var stream = new StringReader(soapEnvelope.Body.ToString()))
                using (var reader = new XmlTextReader(stream))
                {
                    return(InputFormatterResult.Success(
                               new XmlSerializer(context.ModelType).Deserialize(reader)));
                }
        }
Пример #11
0
        /// <inheritdoc />
        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;
            Stream readStream = new NonDisposableStream(request.Body);

            if (!request.Body.CanSeek && !_options.SuppressInputFormatterBuffering)
            {
                // XmlSerializer does synchronous reads. In order to avoid blocking on the stream, we asynchronously
                // read everything into a buffer, and then seek back to the beginning.
                var memoryThreshold = DefaultMemoryThreshold;
                var contentLength   = request.ContentLength.GetValueOrDefault();
                if (contentLength > 0 && contentLength < memoryThreshold)
                {
                    // If the Content-Length is known and is smaller than the default buffer size, use it.
                    memoryThreshold = (int)contentLength;
                }

                readStream = new FileBufferingReadStream(request.Body, memoryThreshold);

                await readStream.DrainAsync(CancellationToken.None);

                readStream.Seek(0L, SeekOrigin.Begin);
            }

            try
            {
                using var xmlReader = CreateXmlReader(readStream, encoding);
                var type = GetSerializableType(context.ModelType);

                var serializer = GetCachedSerializer(type);

                var deserializedObject = serializer.Deserialize(xmlReader);

                // Unwrap only if the original type was wrapped.
                if (type != context.ModelType)
                {
                    if (deserializedObject is IUnwrappable unwrappable)
                    {
                        deserializedObject = unwrappable.Unwrap(declaredType: context.ModelType);
                    }
                }

                return(InputFormatterResult.Success(deserializedObject));
            }
            // XmlSerializer wraps actual exceptions (like FormatException or XmlException) into an InvalidOperationException
            // https://github.com/dotnet/corefx/blob/master/src/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs#L652
            catch (InvalidOperationException exception) when(exception.InnerException != null &&
                                                             exception.InnerException.InnerException == null &&
                                                             string.Equals("Microsoft.GeneratedCode", exception.InnerException.Source, StringComparison.InvariantCulture))
            {
                // Know this was an XML parsing error because the inner Exception was thrown in the (generated)
                // assembly the XmlSerializer uses for parsing. The problem did not arise lower in the stack i.e. it's
                // not (for example) an out-of-memory condition.
                throw new InputFormatterException(Resources.ErrorDeserializingInputData, exception.InnerException);
            }
            catch (InvalidOperationException exception) when(exception.InnerException is FormatException ||
                                                             exception.InnerException is XmlException)
            {
                throw new InputFormatterException(Resources.ErrorDeserializingInputData, exception.InnerException);
            }
            finally
            {
                if (readStream is FileBufferingReadStream fileBufferingReadStream)
                {
                    await fileBufferingReadStream.DisposeAsync();
                }
            }
        }
Пример #12
0
        public async Task Invoke(HttpContext httpContext)
        {
            if (!NetStitchMiddleware.Servers.TryGetValue(options.ServerID, out var server))
            {
                httpContext.Response.ContentType = "text/plain";
                httpContext.Response.StatusCode  = HttpStatus.NotFound;
                byte[] bytes = Encoding.UTF8.GetBytes($"ServerID Not Found : {options.ServerID}");
                httpContext.Response.Body.Write(bytes, 0, bytes.Length);
                return;
            }

            if (httpContext.Request.ContentType == "application/x-msgpack")
            {
                await next(httpContext).ConfigureAwait(false);
            }
            else if (httpContext.Request.ContentType == "application/x-www-form-urlencoded")
            {
                if (server.OperationMap.TryGetValue(httpContext.Request.Path, out var operation))
                {
                    using (var stream = new NonDisposableStream(new MemoryStream()))
                    {
                        var originalStream = httpContext.Response.Body;
                        httpContext.Response.Body = stream;

                        await CallOperationFromContentTypeOfFormUrlencoded(httpContext, server, operation).ConfigureAwait(false);

                        if (httpContext.Response.StatusCode == HttpStatus.OK)
                        {
                            httpContext.Response.ContentType = "application/json";
                            httpContext.Response.Headers.Remove("Content-Encording");
                            var returnType = operation.MethodInfo.ReturnType.GenericTypeArguments.FirstOrDefault();
                            var obj        = MessagePack.LZ4MessagePackSerializer.NonGeneric.Deserialize(returnType, stream);
                            using (var sw = new StreamWriter(originalStream, Encoding.UTF8))
                                using (var jw = new JsonTextWriter(sw))
                                {
                                    JsonSerializer.Create().Serialize(jw, obj);
                                }
                        }
                        else
                        {
                            stream.Position = 0;
                            stream.CopyTo(originalStream);
                        }
                    }
                }
            }
            else if (httpContext.Request.ContentType == "application/json")
            {
                if (server.OperationMap.TryGetValue(httpContext.Request.Path, out var operation))
                {
                    using (var stream = new NonDisposableStream(new MemoryStream()))
                    {
                        var originalStream = httpContext.Response.Body;
                        httpContext.Response.Body = stream;

                        await CallOperationFromContentTypeOfJson(httpContext, server, operation).ConfigureAwait(false);

                        if (httpContext.Response.StatusCode == HttpStatus.OK)
                        {
                            httpContext.Response.ContentType = "application/json";
                            httpContext.Response.Headers.Remove("Content-Encording");
                            var returnType = operation.MethodInfo.ReturnType.GenericTypeArguments.FirstOrDefault();
                            var obj        = MessagePack.LZ4MessagePackSerializer.NonGeneric.Deserialize(returnType, stream);
                            using (var sw = new StreamWriter(originalStream, Encoding.UTF8))
                                using (var jw = new JsonTextWriter(sw))
                                {
                                    JsonSerializer.Create().Serialize(jw, obj);
                                }
                        }
                        else
                        {
                            stream.Position = 0;
                            stream.CopyTo(originalStream);
                        }
                    }
                }
            }
            else
            {
                await CallSwagger(httpContext, server).ConfigureAwait(false);
            }
        }