Exemplo n.º 1
1
        public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead)
        {
            // Arrange
            var loggerMock = GetLogger();

            var formatter =
                new JsonInputFormatter(loggerMock, _serializerSettings, ArrayPool<char>.Shared, _objectPoolProvider);
            var contentBytes = Encoding.UTF8.GetBytes("content");

            var httpContext = GetHttpContext(contentBytes, contentType: requestContentType);
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(string));
            var formatterContext = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: new ModelStateDictionary(),
                metadata: metadata,
                readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);

            // Act
            var result = formatter.CanRead(formatterContext);

            // Assert
            Assert.Equal(expectedCanRead, result);
        }
        public async Task JsonPatchInputFormatter_ReadsMultipleOperations_Successfully()
        {
            // Arrange
            var logger = GetLogger();
            var formatter = new JsonPatchInputFormatter(logger);
            var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}," +
                "{\"op\": \"remove\", \"path\" : \"Customer/Name\"}]";
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(JsonPatchDocument<Customer>));
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                metadata: metadata,
                readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.False(result.HasError);
            var patchDoc = Assert.IsType<JsonPatchDocument<Customer>>(result.Model);
            Assert.Equal("add", patchDoc.Operations[0].op);
            Assert.Equal("Customer/Name", patchDoc.Operations[0].path);
            Assert.Equal("John", patchDoc.Operations[0].value);
            Assert.Equal("remove", patchDoc.Operations[1].op);
            Assert.Equal("Customer/Name", patchDoc.Operations[1].path);
        }
        public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            var request = context.HttpContext.Request;
            using (var reader = new BsonReader(request.Body))
            {
                var successful = true;
                EventHandler<ErrorEventArgs> errorHandler = (sender, eventArgs) =>
                {
                    successful = false;
                    var exception = eventArgs.ErrorContext.Error;
                    eventArgs.ErrorContext.Handled = true;
                };                
                var jsonSerializer = CreateJsonSerializer();
                jsonSerializer.Error += errorHandler;
                var type = context.ModelType;
                object model;
                try
                {
                    model = jsonSerializer.Deserialize(reader, type);
                }
                finally
                {
                    _jsonSerializerPool.Return(jsonSerializer);
                }

                if (successful)
                {
                    return InputFormatterResult.SuccessAsync(model);
                }

                return InputFormatterResult.FailureAsync();
            }
        }
        public Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
        {
            if (context == null)
            throw new ArgumentNullException(nameof(context));

              var request = context.HttpContext.Request;

              if (request.ContentLength == 0)
              {
            return InputFormatterResult.SuccessAsync(null);
              }

              try
              {
            var model = DeSerializationService.DeserializeFromRoot(GetRequestBody(context.HttpContext.Request.Body),
              _inputFormatterOptions);

            return InputFormatterResult.SuccessAsync(model);
              }
              catch (JsonSerializationException)
              {
            context.HttpContext.Response.StatusCode = 422;
            return InputFormatterResult.FailureAsync();
              }
        }
        /// <summary>
        /// Reads the input XML.
        /// </summary>
        /// <param name="context">The input formatter context which contains the body to be read.</param>
        /// <returns>Task which reads the input.</returns>
        public override Task<object> ReadRequestBodyAsync(InputFormatterContext context)
        {
            var request = context.ActionContext.HttpContext.Request;

            MediaTypeHeaderValue requestContentType;
            MediaTypeHeaderValue.TryParse(request.ContentType, out requestContentType);
            var effectiveEncoding = SelectCharacterEncoding(requestContentType);

            using (var xmlReader = CreateXmlReader(new NonDisposableStream(request.Body), effectiveEncoding))
            {
                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)
                {
                    var unwrappable = deserializedObject as IUnwrappable;
                    if (unwrappable != null)
                    {
                        deserializedObject = unwrappable.Unwrap(declaredType: context.ModelType);
                    }
                }

                return Task.FromResult(deserializedObject);
            }
        }
        public async Task JsonPatchInputFormatter_ReadsOneOperation_Successfully()
        {
            // Arrange
            var formatter = new JsonPatchInputFormatter();
            var content = "[{\"op\":\"add\",\"path\":\"Customer/Name\",\"value\":\"John\"}]";
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                modelType: typeof(JsonPatchDocument<Customer>));

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.False(result.HasError);
            var patchDoc = Assert.IsType<JsonPatchDocument<Customer>>(result.Model);
            Assert.Equal("add", patchDoc.Operations[0].op);
            Assert.Equal("Customer/Name", patchDoc.Operations[0].path);
            Assert.Equal("John", patchDoc.Operations[0].value);
        }
        public override bool CanRead(InputFormatterContext context)
        {
            var type = context.ModelType;
            if (type == null)
                throw new ArgumentNullException("type");

            return IsTypeOfIEnumerable(type);
        }
Exemplo n.º 8
0
 public async Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
 {
     using (var requestStream = new StreamReader(context.HttpContext.Request.Body, Encoding.UTF8))
     {
         var requestData = await requestStream.ReadToEndAsync();
         return InputFormatterResult.Success(JsonConvert.DeserializeObject(requestData, context.ModelType, SerializerSettings));
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Attempts to bind the model using formatters.
        /// </summary>
        /// <param name="bindingContext">The <see cref="ModelBindingContext"/>.</param>
        /// <returns>
        /// A <see cref="Task{ModelBindingResult}"/> which when completed returns a <see cref="ModelBindingResult"/>.
        /// </returns>
        private async Task<ModelBindingResult> BindModelCoreAsync([NotNull] ModelBindingContext bindingContext)
        {
            // For compatibility with MVC 5.0 for top level object we want to consider an empty key instead of
            // the parameter name/a custom name. In all other cases (like when binding body to a property) we
            // consider the entire ModelName as a prefix.
            var modelBindingKey = bindingContext.IsTopLevelObject ? string.Empty : bindingContext.ModelName;

            var httpContext = bindingContext.OperationBindingContext.HttpContext;

            var formatterContext = new InputFormatterContext(
                httpContext,
                modelBindingKey,
                bindingContext.ModelState,
                bindingContext.ModelType);
            var formatters = bindingContext.OperationBindingContext.InputFormatters;
            var formatter = formatters.FirstOrDefault(f => f.CanRead(formatterContext));

            if (formatter == null)
            {
                var unsupportedContentType = Resources.FormatUnsupportedContentType(
                    bindingContext.OperationBindingContext.HttpContext.Request.ContentType);
                bindingContext.ModelState.AddModelError(modelBindingKey, unsupportedContentType);

                // This model binder is the only handler for the Body binding source and it cannot run twice. Always
                // tell the model binding system to skip other model binders and never to fall back i.e. indicate a
                // fatal error.
                return ModelBindingResult.Failed(modelBindingKey);
            }

            try
            {
                var previousCount = bindingContext.ModelState.ErrorCount;
                var result = await formatter.ReadAsync(formatterContext);
                var model = result.Model;

                // Ensure a "modelBindingKey" entry exists whether or not formatting was successful.
                bindingContext.ModelState.SetModelValue(modelBindingKey, rawValue: model, attemptedValue: null);

                if (result.HasError)
                {
                    // Formatter encountered an error. Do not use the model it returned. As above, tell the model
                    // binding system to skip other model binders and never to fall back.
                    return ModelBindingResult.Failed(modelBindingKey);
                }

                return ModelBindingResult.Success(modelBindingKey, model);
            }
            catch (Exception ex)
            {
                bindingContext.ModelState.AddModelError(modelBindingKey, ex);

                // This model binder is the only handler for the Body binding source and it cannot run twice. Always
                // tell the model binding system to skip other model binders and never to fall back i.e. indicate a
                // fatal error.
                return ModelBindingResult.Failed(modelBindingKey);
            }
        }
 public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding effectiveEncoding)
 {
     var request = context.HttpContext.Request;
     using (var reader = new StreamReader(request.Body, effectiveEncoding))
     {
         var stringContent = reader.ReadToEnd();
         return InputFormatterResult.SuccessAsync(stringContent);
     }
 }
        public bool CanRead(InputFormatterContext context)
        {
            if (context == null)
            throw new ArgumentNullException(nameof(context));

              var contentTypeString = context.HttpContext.Request.ContentType;

              return string.IsNullOrEmpty(contentTypeString) || contentTypeString == "application/json";
        }
        public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            var request = context.HttpContext.Request;
            string value;
            using (var reader = new StreamReader(request.Body))
            {
                value = reader.ReadToEnd();
            }

            return InputFormatterResult.SuccessAsync(value);
        }
        public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
        {
            var type = context.ModelType;
            var request = context.HttpContext.Request;
            MediaTypeHeaderValue requestContentType = null;
            MediaTypeHeaderValue.TryParse(request.ContentType, out requestContentType);


            var result = ReadStream(type, request.Body);
            return InputFormatterResult.SuccessAsync(result);
        }
        public override bool CanRead(InputFormatterContext context)
        {
            bool result = false;
            MediaTypeHeaderValue requestContentType;
            if (this.CanReadType(context.ModelType) && MediaTypeHeaderValue.TryParse(context.HttpContext.Request.ContentType, out requestContentType))
            {
                if ((string.Compare(requestContentType.Type, "application", true) == 0) && requestContentType.SubType.EndsWith("+json", StringComparison.InvariantCultureIgnoreCase))
                    result = true;
                else
                    result = base.CanRead(context);
            }

            return result;
        }
Exemplo n.º 15
0
        public async Task JsonFormatterReadsSimpleTypes(string content, Type type, object expected)
        {
            // Arrange
            var formatter = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var actionContext = GetActionContext(contentBytes);
            var context = new InputFormatterContext(actionContext, type);

            // Act
            var model = await formatter.ReadAsync(context);

            // Assert
            Assert.Equal(expected, model);
        }
Exemplo n.º 16
0
        public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead)
        {
            // Arrange
            var formatter = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes("content");

            var actionContext = GetActionContext(contentBytes, contentType: requestContentType);
            var formatterContext = new InputFormatterContext(actionContext, typeof(string));

            // Act
            var result = formatter.CanRead(formatterContext);

            // Assert
            Assert.Equal(expectedCanRead, result);
        }
Exemplo n.º 17
0
        public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
        {
            var effectiveEncoding = SelectCharacterEncoding(context);
            if (effectiveEncoding == null)
            {
                return InputFormatterResult.FailureAsync();
            }

            var request = context.HttpContext.Request;
            using (var reader = new StreamReader(request.Body, effectiveEncoding))
            {
                var stringContent = reader.ReadToEnd();
                return InputFormatterResult.SuccessAsync(stringContent);
            }
        }
        public void CanRead_ReturnsTrueOnlyForJsonPatchContentType(string requestContentType, bool expectedCanRead)
        {
            // Arrange
            var formatter = new JsonPatchInputFormatter();
            var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}]";
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var actionContext = GetActionContext(contentBytes, contentType: requestContentType);
            var formatterContext = new InputFormatterContext(actionContext, typeof(JsonPatchDocument<Customer>));

            // Act
            var result = formatter.CanRead(formatterContext);

            // Assert
            Assert.Equal(expectedCanRead, result);
        }
        public async Task JsonPatchInputFormatter_ReadsOneOperation_Successfully()
        {
            // Arrange
            var formatter = new JsonPatchInputFormatter();
            var content = "[{\"op\":\"add\",\"path\":\"Customer/Name\",\"value\":\"John\"}]";
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var actionContext = GetActionContext(contentBytes);
            var context = new InputFormatterContext(actionContext, typeof(JsonPatchDocument<Customer>));

            // Act
            var model = await formatter.ReadAsync(context);

            // Assert
            var patchDoc = Assert.IsType<JsonPatchDocument<Customer>>(model);
            Assert.Equal("add", patchDoc.Operations[0].op);
            Assert.Equal("Customer/Name", patchDoc.Operations[0].path);
            Assert.Equal("John", patchDoc.Operations[0].value);
        }
Exemplo n.º 20
0
        public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead)
        {
            // Arrange
            var formatter = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes("content");

            var httpContext = GetHttpContext(contentBytes, contentType: requestContentType);
            var formatterContext = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: new ModelStateDictionary(),
                modelType: typeof(string));

            // Act
            var result = formatter.CanRead(formatterContext);

            // Assert
            Assert.Equal(expectedCanRead, result);
        }
Exemplo n.º 21
0
        public void MultipartFormatter_CanRead_ReturnsTrueForSupportedMediaTypes(string requestContentType)
        {
            // Arrange
            var formatter = new MultipartFormatter();
            var httpContext = new DefaultHttpContext();
            httpContext.Request.ContentType = requestContentType;

            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(void));
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: new ModelStateDictionary(),
                metadata: metadata);

            // Act
            var result = formatter.CanRead(context);

            // Assert
            Assert.True(result);
        }
Exemplo n.º 22
0
        /// <inheritdoc />
        public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var request = context.HttpContext.Request;
            var selectedEncoding = SelectCharacterEncoding(context);
            if (selectedEncoding == null)
            {
                var message = Resources.FormatUnsupportedContentType(
                    context.HttpContext.Request.ContentType);

                var exception = new UnsupportedContentTypeException(message);
                context.ModelState.AddModelError(context.ModelName, exception, context.Metadata);

                return InputFormatterResult.FailureAsync();
            }

            return ReadRequestBodyAsync(context, selectedEncoding);
        }
        public void DefaultInputFormatterSelectorTests_ReturnsFirstFormatterWhichReturnsTrue()
        {
            // Arrange
            var actionContext = GetActionContext();
            var inputFormatters = new List<IInputFormatter>()
            {
                new TestInputFormatter(false, 0),
                new TestInputFormatter(false, 1),
                new TestInputFormatter(true, 2),
                new TestInputFormatter(true, 3)
            };

            var context = new InputFormatterContext(actionContext, typeof(int));
            var selector = new DefaultInputFormatterSelector();

            // Act
            var selectedFormatter = selector.SelectFormatter(inputFormatters, context);

            // Assert
            var testFormatter = Assert.IsType<TestInputFormatter>(selectedFormatter);
            Assert.Equal(2, testFormatter.Index);
        }
        public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var request = context.HttpContext.Request;

            using (var reader = new StreamReader(request.Body))
            {
                try
                {
                    var content = await reader.ReadToEndAsync();

                    return(await InputFormatterResult.SuccessAsync(content));
                }
                catch
                {
                    return(await InputFormatterResult.FailureAsync());
                }
            }
        }
        public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead)
        {
            // Arrange
            var formatter    = new XmlDataContractSerializerInputFormatter(new MvcOptions());
            var contentBytes = Encoding.UTF8.GetBytes("content");

            var modelState       = new ModelStateDictionary();
            var httpContext      = GetHttpContext(contentBytes, contentType: requestContentType);
            var provider         = new EmptyModelMetadataProvider();
            var metadata         = provider.GetMetadataForType(typeof(string));
            var formatterContext = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                metadata: metadata,
                readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);

            // Act
            var result = formatter.CanRead(formatterContext);

            // Assert
            Assert.Equal(expectedCanRead, result);
        }
        public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var request = context.HttpContext.Request;

            if (!request.Body.CanSeek && !_options.SuppressReadBuffering)
            {
                BufferingHelper.EnableRewind(request);

                await request.Body.DrainAsync(CancellationToken.None);

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

            var result          = MessagePackSerializer.NonGeneric.Deserialize(context.ModelType, request.Body, _options.FormatterResolver);
            var formatterResult = await InputFormatterResult.SuccessAsync(result);

            return(formatterResult);
        }
Exemplo n.º 27
0
 public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
 {
     var mvcOpt= context.HttpContext.RequestServices.GetRequiredService<IOptions<MvcOptions>>().Value;
     var formatters = mvcOpt.InputFormatters;
     TextInputFormatter formatter =null; // the real formatter : SystemTextJsonInput or Newtonsoft
     Endpoint endpoint = context.HttpContext.GetEndpoint();
     if(endpoint.Metadata.GetMetadata<UseSystemTextJsonAttribute>()!= null)
     {
         formatter= formatters.OfType<SystemTextJsonInputFormatter>().FirstOrDefault();
         //formatter = formatter ?? SystemTextJsonInputFormatter
     }
     else if( endpoint.Metadata.GetMetadata<UseNewtonsoftJsonAttribute>() != null){
         // don't use `Of<NewtonsoftJsonInputFormatter>` here because there's a NewtonsoftJsonPatchInputFormatter
         formatter= (NewtonsoftJsonInputFormatter)(formatters
             .Where(f =>typeof(NewtonsoftJsonInputFormatter) == f.GetType())
             .FirstOrDefault());
     }
     else{
         throw new Exception("This formatter is only used for System.Text.Json InputFormatter or NewtonsoftJson InputFormatter");
     }
     var result = await formatter.ReadRequestBodyAsync(context,encoding);
     return result;
 }
        public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream()
        {
            // Arrange
            var expectedException = TestPlatformHelper.IsMono ? typeof(SerializationException) :
                                    typeof(XmlException);
            var expectedMessage = TestPlatformHelper.IsMono ?
                                  "Expected element 'TestLevelTwo' in namespace '', but found Element node 'DummyClass' in namespace ''" :
                                  "The expected encoding 'utf-16LE' does not match the actual encoding 'utf-8'.";
            var inputBytes = Encoding.UTF8.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                                    "<DummyClass><SampleInt>1000</SampleInt></DummyClass>");

            var formatter = new XmlDataContractSerializerInputFormatter();

            var modelState  = new ModelStateDictionary();
            var httpContext = GetHttpContext(inputBytes, contentType: "application/xml; charset=utf-16");

            var context = new InputFormatterContext(httpContext, modelState, typeof(TestLevelOne));

            // Act
            var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context));

            Assert.Equal(expectedMessage, ex.Message);
        }
        public override Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            if (context is null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (encoding is null)
            {
                throw new ArgumentNullException(nameof(encoding));
            }

            var    request = context.HttpContext.Request;
            var    type    = context.ModelType;
            object model;

            try
            {
                using (var reader = context.ReaderFactory(request.Body, encoding))
                {
                    var jsonValue = JsonValue.Parse(reader.ReadToEnd());
                    model = typeof(JsonValue) == type ? jsonValue : serializer.Deserialize(type, jsonValue);
                }
                if (model == null && !context.TreatEmptyInputAsDefaultValue)
                {
                    return(InputFormatterResult.NoValueAsync());
                }
                else
                {
                    return(InputFormatterResult.SuccessAsync(model));
                }
            }
            catch
            {
                return(InputFormatterResult.FailureAsync());
            }
        }
Exemplo n.º 30
0
        public Task <InputFormatterResult> ReadAsync(InputFormatterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var request = context.HttpContext.Request;

            if (request.ContentLength == 0)
            {
                return(InputFormatterResult.SuccessAsync(null));
            }

            var loggerFactory = GetService <ILoggerFactory>(context);
            var logger        = loggerFactory?.CreateLogger <JsonApiInputFormatter>();

            try
            {
                var body           = GetRequestBody(context.HttpContext.Request.Body);
                var jsonApiContext = GetService <IJsonApiContext>(context);
                var model          = JsonApiDeSerializer.Deserialize(body, jsonApiContext);

                if (model == null)
                {
                    logger?.LogError("An error occurred while de-serializing the payload");
                }

                return(InputFormatterResult.SuccessAsync(model));
            }
            catch (JsonSerializationException ex)
            {
                logger?.LogError(new EventId(), ex, "An error occurred while de-serializing the payload");
                context.HttpContext.Response.StatusCode = 422;
                return(InputFormatterResult.FailureAsync());
            }
        }
Exemplo n.º 31
0
        public async Task ReadAsync_AcceptsUTF16Characters()
        {
            // Arrange
            var expectedInt      = 10;
            var expectedString   = "TestString";
            var expectedDateTime = XmlConvert.ToString(DateTime.UtcNow, XmlDateTimeSerializationMode.Utc);

            var input = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>" +
                        "<TestLevelOne><SampleInt>" + expectedInt + "</SampleInt>" +
                        "<sampleString>" + expectedString + "</sampleString>" +
                        "<SampleDate>" + expectedDateTime + "</SampleDate></TestLevelOne>";

            var formatter    = new XmlSerializerInputFormatter();
            var contentBytes = Encoding.Unicode.GetBytes(input);

            var modelState  = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes, contentType: "application/xml; charset=utf-16");
            var provider    = new EmptyModelMetadataProvider();
            var metadata    = provider.GetMetadataForType(typeof(TestLevelOne));
            var context     = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                metadata: metadata);

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.NotNull(result);
            Assert.False(result.HasError);
            var model = Assert.IsType <TestLevelOne>(result.Model);

            Assert.Equal(expectedInt, model.SampleInt);
            Assert.Equal(expectedString, model.sampleString);
            Assert.Equal(XmlConvert.ToDateTime(expectedDateTime, XmlDateTimeSerializationMode.Utc), model.SampleDate);
        }
        public async Task UploadStudentWithParentId_Returns_StudentWithParentId()
        {
            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var formFileCollection         = new FormFileCollection();

            var parentId = Guid.NewGuid().ToString("D");
            var models   = new Dictionary <string, StringValues>();

            models.Add($"{nameof(StudentViewModel.ParentId)}", parentId);

            var formCollection  = new FormCollection(models, formFileCollection);
            var httpContextMock = new Mock <HttpContext>();
            var httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(x => x.Form)
            .Returns(formCollection);

            httpRequestMock.Setup(x => x.ReadFormAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(formCollection);

            httpContextMock.SetupGet(x => x.Request)
            .Returns(httpRequestMock.Object);

            var inputFormatter = new InputFormatterContext(httpContextMock.Object, string.Empty,
                                                           new ModelStateDictionary(), new EmptyModelMetaData(ModelMetadataIdentity.ForType(typeof(StudentViewModel))),
                                                           (stream, encoding) => TextReader.Null);

            var handledResult = await multipartFormDataFormatter
                                .ReadRequestBodyAsync(inputFormatter);

            Assert.IsInstanceOf <InputFormatterResult>(handledResult);

            var student = handledResult.Model as StudentViewModel;

            Assert.NotNull(student);
            Assert.AreEqual(parentId, student.ParentId?.ToString("D"));
        }
        public async Task UploadStudentTypeWithEnumAsText_Returns_StudentWithTypeEnum()
        {
            var goodStudentType            = StudentTypes.Good;
            var multipartFormDataFormatter = new MultipartFormDataFormatter();
            var formFileCollection         = new FormFileCollection();

            var models = new Dictionary <string, StringValues>();

            models.Add(nameof(StudentViewModel.Type), Enum.GetName(typeof(StudentTypes), goodStudentType));

            var formCollection  = new FormCollection(models, formFileCollection);
            var httpContextMock = new Mock <HttpContext>();
            var httpRequestMock = new Mock <HttpRequest>();

            httpRequestMock.Setup(x => x.Form)
            .Returns(formCollection);

            httpRequestMock.Setup(x => x.ReadFormAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(formCollection);

            httpContextMock.SetupGet(x => x.Request)
            .Returns(httpRequestMock.Object);

            var inputFormatter = new InputFormatterContext(httpContextMock.Object, string.Empty,
                                                           new ModelStateDictionary(), new EmptyModelMetaData(ModelMetadataIdentity.ForType(typeof(StudentViewModel))),
                                                           (stream, encoding) => TextReader.Null);

            var handledResult = await multipartFormDataFormatter
                                .ReadRequestBodyAsync(inputFormatter);

            Assert.IsInstanceOf <InputFormatterResult>(handledResult);

            var student = handledResult.Model as StudentViewModel;

            Assert.NotNull(student);
            Assert.AreEqual(goodStudentType, student.Type);
        }
Exemplo n.º 34
0
        /// <inheritdoc/>
        public override bool CanRead(InputFormatterContext context)
        {
            if (context == null)
            {
                throw Error.ArgumentNull("context");
            }

            HttpRequest request = context.HttpContext.Request;

            if (request == null)
            {
                throw Error.InvalidOperation(SRResources.ReadFromStreamAsyncMustHaveRequest);
            }

            // Ignore non-OData requests.
            if (request.ODataFeature().Path == null)
            {
                return(false);
            }

            Type type = context.ModelType;

            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            ODataDeserializerProvider deserializerProvider = request.GetRequestContainer().GetRequiredService <ODataDeserializerProvider>();

            return(ODataInputFormatterHelper.CanReadType(
                       type,
                       request.GetModel(),
                       request.ODataFeature().Path,
                       _payloadKinds,
                       (objectType) => deserializerProvider.GetEdmTypeDeserializer(objectType),
                       (objectType) => deserializerProvider.GetODataDeserializer(objectType, request)));
        }
Exemplo n.º 35
0
        /// <summary>
        ///		Deserialise the response message's content into the specified CLR data type using the most appropriate formatter.
        /// </summary>
        /// <typeparam name="TBody">
        ///		The CLR data type into which the body will be deserialised.
        /// </typeparam>
        /// <param name="responseMessage">
        ///		The response message.
        /// </param>
        /// <param name="formatters">
        ///		The collection of content formatters from which to select an appropriate formatter.
        /// </param>
        /// <returns>
        ///		The deserialised message body.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        ///		An appropriate formatter could not be found in the request's list of formatters.
        /// </exception>
        public static async Task <TBody> ReadContentAsAsync <TBody>(this HttpResponseMessage responseMessage, IFormatterCollection formatters)
        {
            if (responseMessage == null)
            {
                throw new ArgumentNullException(nameof(responseMessage));
            }

            if (formatters == null)
            {
                throw new ArgumentNullException(nameof(formatters));
            }

            responseMessage.EnsureHasBody();

            InputFormatterContext readContext   = responseMessage.Content.CreateInputFormatterContext <TBody>();
            IInputFormatter       readFormatter = formatters.FindInputFormatter(readContext);

            if (readFormatter == null)
            {
                throw new InvalidOperationException($"None of the supplied formatters can read data of type '{readContext.DataType.FullName}' from media type '{readContext.MediaType}'.");
            }

            return(await responseMessage.ReadContentAsAsync <TBody>(readFormatter, readContext).ConfigureAwait(false));
        }
Exemplo n.º 36
0
        public override Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            var request = context.HttpContext.Request;

            using (var reader = new BsonReader(request.Body))
            {
                reader.ReadRootValueAsArray = IsEnumerable(context.ModelType);

                var successful = true;
                EventHandler <ErrorEventArgs> errorHandler = (sender, eventArgs) =>
                {
                    successful = false;
                    var exception = eventArgs.ErrorContext.Error;
                    eventArgs.ErrorContext.Handled = true;
                };
                var jsonSerializer = CreateJsonSerializer();
                jsonSerializer.Error += errorHandler;
                var    type = context.ModelType;
                object model;
                try
                {
                    model = jsonSerializer.Deserialize(reader, type);
                }
                finally
                {
                    _jsonSerializerPool.Return(jsonSerializer);
                }

                if (successful)
                {
                    return(InputFormatterResult.SuccessAsync(model));
                }

                return(InputFormatterResult.FailureAsync());
            }
        }
Exemplo n.º 37
0
        public async Task ReadAsync_UsesContentTypeCharSet_ToReadStream()
        {
            // Arrange
            var expectedException = TestPlatformHelper.IsMono ? typeof(InvalidOperationException) :
                                    typeof(XmlException);
            var expectedMessage = TestPlatformHelper.IsMono ?
                                  "There is an error in XML document." :
                                  "The expected encoding 'utf-16LE' does not match the actual encoding 'utf-8'.";

            var inputBytes = Encodings.UTF8EncodingWithoutBOM.GetBytes("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
                                                                       "<DummyClass><SampleInt>1000</SampleInt></DummyClass>");

            var formatter = new XmlSerializerInputFormatter();

            var modelState  = new ModelStateDictionary();
            var httpContext = GetHttpContext(inputBytes, contentType: "application/xml; charset=utf-16");

            var context = new InputFormatterContext(httpContext, modelState, typeof(TestLevelOne));

            // Act and Assert
            var ex = await Assert.ThrowsAsync(expectedException, () => formatter.ReadAsync(context));

            Assert.Equal(expectedMessage, ex.Message);
        }
Exemplo n.º 38
0
        /// <inheritdoc/>
        public override bool CanRead(InputFormatterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            HttpRequest request = context.HttpContext.Request;

            if (request == null)
            {
                throw Error.InvalidOperation(SRResources.ReadFromStreamAsyncMustHaveRequest);
            }

            // Ignore non-OData requests.
            if (request.ODataFeature().Path == null)
            {
                return(false);
            }

            Type type = context.ModelType;

            if (type == null)
            {
                throw Error.ArgumentNull("type");
            }

            ODataDeserializer deserializer = GetDeserializer(request, type, out _);

            if (deserializer != null)
            {
                return(_payloadKinds.Contains(deserializer.ODataPayloadKind));
            }

            return(false);
        }
Exemplo n.º 39
0
        /// <inheritdoc />
        public virtual bool CanRead(InputFormatterContext context)
        {
            if (SupportedMediaTypes.Count == 0)
            {
                throw new InvalidOperationException(
                          $"No media types found in '{GetType().FullName}.{nameof(SupportedMediaTypes)}'. Add at least one media type to the list of supported media types.");
            }

            if (!CanReadType(context.ModelType))
            {
                return(false);
            }

            var contentType = context.MazeContext.Request.ContentType;

            if (string.IsNullOrEmpty(contentType))
            {
                return(false);
            }

            // Confirm the request's content type is more specific than a media type this formatter supports e.g. OK if
            // client sent "text/plain" data and this formatter supports "text/*".
            return(IsSubsetOfAnySupportedContentType(contentType));
        }
Exemplo n.º 40
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;

            using (var reader = new StreamReader(request.Body, encoding))
            {
                try
                {
                    var line = await reader.ReadLineAsync();

                    var split   = line.Split(new char[] { ';' });
                    var payment = new Payment()
                    {
                        Id          = (split[0]),
                        Name        = split[1],
                        Description = split[2]
                    };

                    return(await InputFormatterResult.SuccessAsync(payment));
                }
                catch
                {
                    return(await InputFormatterResult.FailureAsync());
                }
            }
        }
Exemplo n.º 41
0
        /// <inheritdoc/>
        public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            await SyncContext.Clear;

            var request = context.HttpContext.Request;

            if (request.Body == null)
            {
                return(await InputFormatterResult.SuccessAsync(null));
            }
            else
            {
                var result = await RoundtripDataFactory.TryCreateFromAsync(context.ModelType, request.Body, Encoding.UTF8);

                if (result.Item1)
                {
                    return(await InputFormatterResult.SuccessAsync(result.Item2));
                }
                else
                {
                    return(await InputFormatterResult.SuccessAsync(NeonHelper.JsonDeserialize(context.ModelType, Encoding.UTF8.GetString(await request.Body.ReadToEndAsync()))));
                }
            }
        }
        public void DefaultInputFormatterSelectorTests_ReturnsFirstFormatterWhichReturnsTrue()
        {
            // Arrange
            var actionContext = GetActionContext();
            var context       = new InputFormatterContext(actionContext, typeof(int));

            actionContext.InputFormatters = new List <IInputFormatter>()
            {
                new TestInputFormatter(false, 0),
                new TestInputFormatter(false, 1),
                new TestInputFormatter(true, 2),
                new TestInputFormatter(true, 3)
            };

            var selector = new DefaultInputFormatterSelector();

            // Act
            var selectedFormatter = selector.SelectFormatter(context);

            // Assert
            var testFormatter = Assert.IsType <TestInputFormatter>(selectedFormatter);

            Assert.Equal(2, testFormatter.Index);
        }
Exemplo n.º 43
0
    /// <inheritdoc />
    public virtual Task <InputFormatterResult> ReadAsync(InputFormatterContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        var canHaveBody = context.HttpContext.Features.Get <IHttpRequestBodyDetectionFeature>()?.CanHaveBody;

        // In case the feature is not registered
        canHaveBody ??= context.HttpContext.Request.ContentLength != 0;

        if (canHaveBody is false)
        {
            if (context.TreatEmptyInputAsDefaultValue)
            {
                return(InputFormatterResult.SuccessAsync(GetDefaultValueForType(context.ModelType)));
            }

            return(InputFormatterResult.NoValueAsync());
        }

        return(ReadRequestBodyAsync(context));
    }
Exemplo n.º 44
0
        internal static async Task <object> ReadAsync(ODataInputFormatter formatter, string entity, Type valueType, HttpRequest request, string mediaType)
        {
            StringContent content = new StringContent(entity);

            content.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType);

            Stream stream = await content.ReadAsStreamAsync();

            Func <Stream, Encoding, TextReader> readerFactor = (s, e) =>
            {
                return(new StreamReader(stream));
            };

            request.Body = stream;

            ModelStateDictionary   modelState = new ModelStateDictionary();
            IModelMetadataProvider provider   = request.HttpContext.RequestServices.GetService <IModelMetadataProvider>();
            ModelMetadata          metaData   = provider.GetMetadataForType(valueType);
            InputFormatterContext  context    = new InputFormatterContext(request.HttpContext, "Any", modelState, metaData, readerFactor);

            InputFormatterResult result = await formatter.ReadAsync(context);

            return(result.Model);
        }
Exemplo n.º 45
0
        public Task <InputFormatterResult> ReadAsync(InputFormatterContext context)
        {
            try
            {
                BitcoinStream bs   = new BitcoinStream(context.HttpContext.Request.Body, false);
                Type          type = context.ModelType;

                var signature = type == typeof(TransactionSignature);
                if (context.ModelType.IsArray)
                {
                    var elementType = context.ModelType.GetElementType();
                    type = typeof(ArrayWrapper <>).MakeGenericType(elementType);
                }
                if (signature)
                {
                    type = typeof(SignatureWrapper);
                }

                var result = _Parse.MakeGenericMethod(type).Invoke(null, new object[] { bs });

                if (context.ModelType.IsArray)
                {
                    var getElements = type.GetTypeInfo().GetProperty("Elements", BindingFlags.Instance | BindingFlags.Public).GetGetMethod();
                    result = getElements.Invoke(result, new object[0]);
                }
                if (signature)
                {
                    result = ((SignatureWrapper)result).Signature;
                }
                return(InputFormatterResult.SuccessAsync(result));
            }
            catch
            {
                return(InputFormatterResult.FailureAsync());
            }
        }
Exemplo n.º 46
0
        public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context,
                                                                               Encoding encoding)
        {
            var descriptor = context
                             .ModelType
                             .GetProperty(
                "Descriptor",
                BindingFlags.Public | BindingFlags.Static)
                             .GetValue(null, null)
                             as MessageDescriptor;
            var httpContext = context.HttpContext;

            using var reader = new StreamReader(httpContext.Request.Body, encoding);
            var json = await reader.ReadToEndAsync();

            var res = JsonParser.Default.Parse(json, descriptor);

            if (!res.IsInitialized())
            {
                throw new ProtoJsonInputFormatterException($"Proto '{descriptor.Name}' was not initialized correctly.");
            }

            return(InputFormatterResult.Success(res));
        }
Exemplo n.º 47
0
    public void SelectCharacterEncoding_ReturnsFirstEncoding_IfContentTypeIsMissingInvalidOrDoesNotHaveEncoding(
        string contentType)
    {
        // Arrange
        var formatter = new TestFormatter();

        formatter.SupportedEncodings.Add(Encoding.UTF8);
        formatter.SupportedEncodings.Add(Encoding.UTF32);

        var context = new InputFormatterContext(
            new DefaultHttpContext(),
            "something",
            new ModelStateDictionary(),
            new EmptyModelMetadataProvider().GetMetadataForType(typeof(object)),
            (stream, encoding) => new StreamReader(stream, encoding));

        context.HttpContext.Request.ContentType = contentType;

        // Act
        var result = formatter.TestSelectCharacterEncoding(context);

        // Assert
        Assert.Equal(Encoding.UTF8, result);
    }
Exemplo n.º 48
0
        public Task <InputFormatterResult> ReadAsync(InputFormatterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var request = context.HttpContext.Request;

            if (request.ContentLength == 0)
            {
                return(InputFormatterResult.SuccessAsync(null));
            }

            try
            {
                var body = GetRequestBody(context.HttpContext.Request.Body);

                var model = _jsonApiContext.IsRelationshipPath ?
                            _deSerializer.DeserializeRelationship(body) :
                            _deSerializer.Deserialize(body);

                if (model == null)
                {
                    _logger?.LogError("An error occurred while de-serializing the payload");
                }

                return(InputFormatterResult.SuccessAsync(model));
            }
            catch (Exception ex)
            {
                _logger?.LogError(new EventId(), ex, "An error occurred while de-serializing the payload");
                context.ModelState.AddModelError(context.ModelName, ex, context.Metadata);
                return(InputFormatterResult.FailureAsync());
            }
        }
Exemplo n.º 49
0
        public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            HttpRequest request = context.HttpContext.Request;
            bool        flag    = _options.SuppressInputFormatterBuffering;

            if (!request.Body.CanSeek && !flag)
            {
                request.EnableBuffering();
                await request.Body.DrainAsync(CancellationToken.None);

                request.Body.Seek(0L, SeekOrigin.Begin);
            }
            using (TextReader reader = context.ReaderFactory(request.Body, encoding))
            {
                using (JsonTextReader jsonTextReader = new JsonTextReader(reader))
                {
                    jsonTextReader.ArrayPool  = _charPool;
                    jsonTextReader.CloseInput = false;
                    Type           modelType      = context.ModelType;
                    JsonSerializer jsonSerializer = CreateJsonSerializer();
                    Request        model;
                    try
                    {
                        model = jsonSerializer.Deserialize <Request>(jsonTextReader);
                    }
                    finally
                    {
                        ReleaseJsonSerializer(jsonSerializer);
                    }

                    switch (model?.Data)
                    {
                    case null when context.TreatEmptyInputAsDefaultValue:
                        return(await InputFormatterResult.SuccessAsync(model));

                    case null:
                        return(await InputFormatterResult.NoValueAsync());
                    }

                    string expectedType = modelType.GetCustomAttributes <ResourceTypeAttribute>().FirstOrDefault()?.Type;

                    if (!string.IsNullOrWhiteSpace(model.Data.Type) && model.Data.Type.Equals(expectedType, StringComparison.OrdinalIgnoreCase))
                    {
                        return(await InputFormatterResult.SuccessAsync(model.Data.Attributes.ToObject(modelType)));
                    }

                    BusinessApplicationException exception        = new BusinessApplicationException(ExceptionType.BadRequest, ErrorCodes.ResourceType, "The provided resource type is invalid");
                    ApplicationError             applicationError = new ApplicationError
                    {
                        Exception      = exception,
                        HttpStatusCode = HttpStatusCode.BadRequest
                    };
                    string response = JsonConvert.SerializeObject(FormattedError.Create(applicationError.FormatError()), _jsonSerializerSettings);

                    context.HttpContext.Response.Clear();
                    context.HttpContext.Response.StatusCode  = (int)HttpStatusCode.BadRequest;
                    context.HttpContext.Response.ContentType = new MediaTypeHeaderValue("application/json").ToString();

                    await context.HttpContext.Response.WriteAsync(response);

                    throw exception;
                }
            }
        }
Exemplo n.º 50
0
        public async Task JsonFormatterReadsSimpleTypes(string content, Type type, object expected)
        {
            // Arrange
            var formatter = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var httpContext = GetHttpContext(contentBytes);
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: new ModelStateDictionary(),
                modelType: type);

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.False(result.HasError);
            Assert.Equal(expected, result.Model);
        }
        /// <summary>
        /// Called during deserialization to get the <see cref="BsonReader"/>.
        /// </summary>
        /// <param name="context">The <see cref="InputFormatterContext"/> for the read.</param>
        /// <param name="readStream">The <see cref="Stream"/> from which to read.</param>
        /// <returns>The <see cref="BsonReader"/> used during deserialization.</returns>
        protected virtual BsonReader CreateBsonReader(
            InputFormatterContext context,
            Stream readStream)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (readStream == null)
            {
                throw new ArgumentNullException(nameof(readStream));
            }

            return new BsonReader(readStream);
        }
Exemplo n.º 52
0
        public async Task CustomSerializerSettingsObject_TakesEffect()
        {
            // Arrange
            // missing password property here
            var contentBytes = Encoding.UTF8.GetBytes("{ \"UserName\" : \"John\"}");

            var jsonFormatter = new JsonInputFormatter();
            // by default we ignore missing members, so here explicitly changing it
            jsonFormatter.SerializerSettings = new JsonSerializerSettings()
            {
                MissingMemberHandling = MissingMemberHandling.Error
            };

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes, "application/json;charset=utf-8");
            var inputFormatterContext = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                modelType: typeof(UserLogin));

            // Act
            var result = await jsonFormatter.ReadAsync(inputFormatterContext);

            // Assert
            Assert.True(result.HasError);
            Assert.False(modelState.IsValid);

            var modelErrorMessage = modelState.Values.First().Errors[0].Exception.Message;
            Assert.Contains("Required property 'Password' not found in JSON", modelErrorMessage);
        }
Exemplo n.º 53
0
        public async Task ReadAsync_UsesTryAddModelValidationErrorsToModelState()
        {
            // Arrange
            var content = "{name: 'Person Name', Age: 'not-an-age'}";
            var formatter = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                modelType: typeof(User));

            modelState.MaxAllowedErrors = 3;
            modelState.AddModelError("key1", "error1");
            modelState.AddModelError("key2", "error2");

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.True(result.HasError);
            Assert.False(modelState.ContainsKey("age"));
            var error = Assert.Single(modelState[""].Errors);
            Assert.IsType<TooManyModelErrorsException>(error.Exception);
        }
Exemplo n.º 54
0
        public async Task ReadAsync_AddsModelValidationErrorsToModelState()
        {
            // Arrange
            var content = "{name: 'Person Name', Age: 'not-an-age'}";
            var formatter = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                modelType: typeof(User));

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.True(result.HasError);
            Assert.Equal(
                "Could not convert string to decimal: not-an-age. Path 'Age', line 1, position 39.",
                modelState["Age"].Errors[0].Exception.Message);
        }
Exemplo n.º 55
0
        public async Task JsonFormatterReadsComplexTypes()
        {
            // Arrange
            var content = "{name: 'Person Name', Age: '30'}";
            var formatter = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var httpContext = GetHttpContext(contentBytes);
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: new ModelStateDictionary(),
                modelType: typeof(User));

            // Act
            var result = await formatter.ReadAsync(context);

            // Assert
            Assert.False(result.HasError);
            var userModel = Assert.IsType<User>(result.Model);
            Assert.Equal("Person Name", userModel.Name);
            Assert.Equal(30, userModel.Age);
        }
Exemplo n.º 56
0
 public bool CanRead(InputFormatterContext context) => context.HttpContext.Request.ContentType.StartsWith("application/json");
Exemplo n.º 57
0
        /// <summary>
        /// If the request has OData v3 headers in it, then process using V3 deserializer provider.
        /// Otherwise, process as base class.
        /// </summary>
        /// <param name="context">InputFormatter context</param>
        /// <param name="encoding">Encoding of request body</param>
        /// <returns>InputFormatterResult</returns>
        public override Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            Type type = context.ModelType;

            if (type == null)
            {
                throw new ArgumentException("Model type for this request body is null", nameof(type));
            }

            HttpRequest request = context.HttpContext.Request;

            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            // If content length is 0 then return default value for this type
            RequestHeaders contentHeaders = request.GetTypedHeaders();
            object         defaultValue   = GetDefaultValueForType(type);

            if (contentHeaders == null || contentHeaders.ContentLength == 0)
            {
                return(Task.FromResult(InputFormatterResult.Success(defaultValue)));
            }

            try
            {
                Func <ODataDeserializerContext> getODataDeserializerContext = () =>
                {
                    return(new ODataDeserializerContext
                    {
                        Request = request,
                    });
                };

                Action <Exception> logErrorAction = (ex) =>
                {
                    ILogger logger = context.HttpContext.RequestServices.GetService <ILogger>();
                    if (logger == null)
                    {
                        throw ex;
                    }

                    logger.LogError(ex, String.Empty);
                };


                List <IDisposable> toDispose = new List <IDisposable>();

                IServiceProvider          fakeProvider         = (new ServiceCollection()).BuildServiceProvider();
                ODataDeserializerProvider deserializerProvider = new ODataMigrationDeserializerProvider(fakeProvider);

                object result = ReadFromStream(
                    type,
                    defaultValue,
                    request.GetModel(),
                    GetBaseAddressInternal(request),
                    request,
                    () => ODataMigrationMessageWrapper.Create(request.Body, request.Headers, request.GetODataContentIdMapping(), request.GetRequestContainer()),
                    (objectType) => deserializerProvider.GetEdmTypeDeserializer(objectType),
                    (objectType) => deserializerProvider.GetODataDeserializer(objectType, request),
                    getODataDeserializerContext,
                    (disposable) => toDispose.Add(disposable),
                    logErrorAction);

                foreach (IDisposable obj in toDispose)
                {
                    obj.Dispose();
                }

                return(Task.FromResult(InputFormatterResult.Success(result)));
            }
            catch (Exception ex)
            {
                context.ModelState.AddModelError(context.ModelName, ex, context.Metadata);
                return(Task.FromResult(InputFormatterResult.Failure()));
            }
        }
 public override bool CanRead(InputFormatterContext context)
 {
     return(true);
 }
Exemplo n.º 59
0
 public override Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context,
                                                                  Encoding encoding)
 {
     return(base.ReadRequestBodyAsync(context, encoding));
 }
        /// <inheritdoc />
        public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var request = context.HttpContext.Request;
            using (var bsonReader = CreateBsonReader(context, request.Body))
            {
                bsonReader.CloseInput = false;

                var successful = true;
                EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> errorHandler = (sender, eventArgs) =>
                {
                    successful = false;

                    var exception = eventArgs.ErrorContext.Error;

                    // Handle path combinations such as "" + "Property", "Parent" + "Property", or "Parent" + "[12]".
                    var key = eventArgs.ErrorContext.Path;
                    if (!string.IsNullOrEmpty(context.ModelName))
                    {
                        if (string.IsNullOrEmpty(eventArgs.ErrorContext.Path))
                        {
                            key = context.ModelName;
                        }
                        else if (eventArgs.ErrorContext.Path[0] == '[')
                        {
                            key = context.ModelName + eventArgs.ErrorContext.Path;
                        }
                        else
                        {
                            key = context.ModelName + "." + eventArgs.ErrorContext.Path;
                        }
                    }

                    var metadata = GetPathMetadata(context.Metadata, eventArgs.ErrorContext.Path);
                    context.ModelState.TryAddModelError(key, eventArgs.ErrorContext.Error, metadata);

                    // Error must always be marked as handled
                    // Failure to do so can cause the exception to be rethrown at every recursive level and
                    // overflow the stack for x64 CLR processes
                    eventArgs.ErrorContext.Handled = true;
                };

                var type = context.ModelType;
                var jsonSerializer = CreateJsonSerializer();
                jsonSerializer.Error += errorHandler;

                object model;
                try
                {
                    model = jsonSerializer.Deserialize(bsonReader, type);
                }
                finally
                {
                    // Clean up the error handler in case CreateJsonSerializer() reuses a serializer
                    jsonSerializer.Error -= errorHandler;
                }

                if (successful)
                {
                    return InputFormatterResult.SuccessAsync(model);
                }

                return InputFormatterResult.FailureAsync();
            }
        }