/// <inheritdoc />
        public override bool CanRead(InputFormatterContext context)
        {
            if (!typeof(IJsonPatchDocument).IsAssignableFrom(context.ModelType) ||
                !context.ModelType.IsGenericType())
            {
                return false;
            }

            return base.CanRead(context);
        }
示例#2
0
        /// <inheritdoc />
        public virtual async Task<object> ReadAsync(InputFormatterContext context)
        {
            var request = context.HttpContext.Request;
            if (request.ContentLength == 0)
            {
                return GetDefaultValueForType(context.ModelType);
            }

            return await ReadRequestBodyAsync(context);
        }
示例#3
0
        /// <inheritdoc />
        public override bool CanRead(InputFormatterContext context)
        {
            var modelTypeInfo = context.ModelType.GetTypeInfo();
            if (!typeof(IJsonPatchDocument).GetTypeInfo().IsAssignableFrom(modelTypeInfo) ||
                !modelTypeInfo.IsGenericType)
            {
                return false;
            }

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

            object result = Model.Deserialize(context.ActionContext.HttpContext.Request.Body, null, type);

            return Task.FromResult(result);
        }
示例#5
0
        public override Task<object> ReadRequestBodyAsync(InputFormatterContext context)
        {
            var request = context.HttpContext.Request;
            MediaTypeHeaderValue requestContentType = null;
            MediaTypeHeaderValue.TryParse(request.ContentType, out requestContentType);
            var effectiveEncoding = SelectCharacterEncoding(requestContentType);

            using (var reader = new StreamReader(request.Body, effectiveEncoding))
            {
                var stringContent = reader.ReadToEnd();
                return Task.FromResult<object>(stringContent);
            }
        }
示例#6
0
        /// <inheritdoc />
        public virtual bool CanRead(InputFormatterContext context)
        {
            if (!CanReadType(context.ModelType))
            {
                return false;
            }

            var contentType = context.HttpContext.Request.ContentType;
            MediaTypeHeaderValue requestContentType;
            if (!MediaTypeHeaderValue.TryParse(contentType, out requestContentType))
            {
                return false;
            }

            return SupportedMediaTypes
                            .Any(supportedMediaType => supportedMediaType.IsSubsetOf(requestContentType));
        }
        /// <inheritdoc />
        public override Task<object> ReadRequestBodyAsync(InputFormatterContext context)
        {
            var type = context.ModelType;
            var request = context.HttpContext.Request;

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

                var jsonSerializer = CreateJsonSerializer();

                EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> errorHandler = null;
                errorHandler = (sender, e) =>
                {
                    var exception = e.ErrorContext.Error;
                    context.ModelState.TryAddModelError(e.ErrorContext.Path, e.ErrorContext.Error);

                    // 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
                    e.ErrorContext.Handled = true;
                };
                jsonSerializer.Error += errorHandler;

                try
                {
                    return Task.FromResult(jsonSerializer.Deserialize(bsonReader, type));
                }
                finally
                {
                    // Clean up the error handler in case CreateJsonSerializer() reuses a serializer
                    if (errorHandler != null)
                    {
                        jsonSerializer.Error -= errorHandler;
                    }
                }
            }
        }
示例#8
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 actionContext = GetActionContext(contentBytes);
            var metadata      = new EmptyModelMetadataProvider().GetMetadataForType(typeof(User));
            var context       = new InputFormatterContext(actionContext, metadata.ModelType);

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

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

            // Assert
            Assert.False(actionContext.ModelState.ContainsKey("age"));
            var error = Assert.Single(actionContext.ModelState[""].Errors);

            Assert.IsType <TooManyModelErrorsException>(error.Exception);
        }
示例#9
0
        public async Task JsonPatchInputFormatter_ReadsMultipleOperations_Successfully()
        {
            // Arrange
            var formatter = new JsonPatchInputFormatter();
            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 context     = new InputFormatterContext(httpContext, modelState, 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);
            Assert.Equal("remove", patchDoc.Operations[1].op);
            Assert.Equal("Customer/Name", patchDoc.Operations[1].path);
        }
示例#10
0
 /// <summary>
 /// Called during deserialization to get the <see cref="JsonReader"/>.
 /// </summary>
 /// <param name="context">The <see cref="InputFormatterContext"/> for the read.</param>
 /// <param name="readStream">The <see cref="Stream"/> from which to read.</param>
 /// <param name="effectiveEncoding">The <see cref="Encoding"/> to use when reading.</param>
 /// <returns>The <see cref="JsonReader"/> used during deserialization.</returns>
 public virtual JsonReader CreateJsonReader([NotNull] InputFormatterContext context,
                                            [NotNull] Stream readStream,
                                            [NotNull] Encoding effectiveEncoding)
 {
     return(new JsonTextReader(new StreamReader(readStream, effectiveEncoding)));
 }
示例#11
0
 /// <summary>
 /// Reads the request body.
 /// </summary>
 /// <param name="context">The <see cref="InputFormatterContext"/> associated with the call.</param>
 /// <returns>A task which can read the request body.</returns>
 public abstract Task<object> ReadRequestBodyAsync(InputFormatterContext context);
 public bool CanRead(InputFormatterContext context)
 {
     throw new NotImplementedException();
 }
 public Task<object> ReadAsync(InputFormatterContext context)
 {
     throw new NotImplementedException();
 }
示例#14
0
 /// <summary>
 /// Reads the request body.
 /// </summary>
 /// <param name="context">The <see cref="InputFormatterContext"/> associated with the call.</param>
 /// <returns>A task which can read the request body.</returns>
 public abstract Task <object> ReadRequestBodyAsync(InputFormatterContext context);
 public override bool CanRead(InputFormatterContext context)
 {
     return true;
 }
示例#16
0
 public override Task <object> ReadRequestBodyAsync(InputFormatterContext context)
 {
     throw new InvalidOperationException("Your input is bad!");
 }
 /// <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)
 {
     return new BsonReader(readStream);
 }
 public Task <object> ReadAsync(InputFormatterContext context)
 {
     throw new NotImplementedException();
 }
 public bool CanRead(InputFormatterContext context)
 {
     throw new NotImplementedException();
 }