コード例 #1
0
    public async Task ReadAsync_RegistersFileStreamForDisposal()
    {
        // Arrange
        var formatter = new NewtonsoftJsonInputFormatter(
            GetLogger(),
            _serializerSettings,
            ArrayPool <char> .Shared,
            _objectPoolProvider,
            new MvcOptions(),
            new MvcNewtonsoftJsonOptions());
        var         httpContext        = new Mock <HttpContext>();
        IDisposable registerForDispose = null;

        var content = Encoding.UTF8.GetBytes("\"Hello world\"");

        httpContext.Setup(h => h.Request.Body).Returns(new NonSeekableReadStream(content, allowSyncReads: false));
        httpContext.Setup(h => h.Request.ContentType).Returns("application/json");
        httpContext.Setup(h => h.Response.RegisterForDispose(It.IsAny <IDisposable>()))
        .Callback((IDisposable disposable) => registerForDispose = disposable)
        .Verifiable();

        var formatterContext = CreateInputFormatterContext(typeof(string), httpContext.Object);

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

        // Assert
        Assert.Equal("Hello world", result.Model);
        Assert.NotNull(registerForDispose);
        Assert.IsType <FileBufferingReadStream>(registerForDispose);
        httpContext.Verify();
    }
コード例 #2
0
    public async Task ReadAsync_DoesNotRethrowOverflowExceptions()
    {
        // Arrange
        _serializerSettings.Converters.Add(new IsoDateTimeConverter());

        var formatter = new NewtonsoftJsonInputFormatter(
            GetLogger(),
            _serializerSettings,
            ArrayPool <char> .Shared,
            _objectPoolProvider,
            new MvcOptions(),
            new MvcNewtonsoftJsonOptions());

        var contentBytes = Encoding.UTF8.GetBytes("{\"shortValue\":\"32768\"}");
        var httpContext  = GetHttpContext(contentBytes);

        var formatterContext = CreateInputFormatterContext(typeof(TypeWithPrimitives), httpContext);

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

        // Assert
        Assert.True(result.HasError);
        Assert.False(formatterContext.ModelState.IsValid);

        var modelError = Assert.Single(formatterContext.ModelState["shortValue"].Errors);

        Assert.Null(modelError.Exception);
        Assert.Equal("The supplied value is invalid.", modelError.ErrorMessage);
    }
コード例 #3
0
    public async Task ReadAsync_AllowInputFormatterExceptionMessages_DoesNotWrapJsonInputExceptions()
    {
        // Arrange
        var formatter = new NewtonsoftJsonInputFormatter(
            GetLogger(),
            _serializerSettings,
            ArrayPool <char> .Shared,
            _objectPoolProvider,
            new MvcOptions(),
            new MvcNewtonsoftJsonOptions()
        {
            AllowInputFormatterExceptionMessages = true,
        });

        var contentBytes = Encoding.UTF8.GetBytes("{");
        var httpContext  = GetHttpContext(contentBytes);

        var formatterContext = CreateInputFormatterContext(typeof(User), httpContext);

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

        // Assert
        Assert.True(result.HasError);
        Assert.True(!formatterContext.ModelState.IsValid);
        Assert.True(formatterContext.ModelState.ContainsKey(string.Empty));

        var modelError = formatterContext.ModelState[string.Empty].Errors.Single();

        Assert.Null(modelError.Exception);
        Assert.NotEmpty(modelError.ErrorMessage);
    }
コード例 #4
0
    public async Task Constructor_BuffersRequestBody_UsingDefaultOptions()
    {
        // Arrange
        var formatter = new NewtonsoftJsonInputFormatter(
            GetLogger(),
            _serializerSettings,
            ArrayPool <char> .Shared,
            _objectPoolProvider,
            new MvcOptions(),
            new MvcNewtonsoftJsonOptions());

        var content      = "{name: 'Person Name', Age: '30'}";
        var contentBytes = Encoding.UTF8.GetBytes(content);
        var httpContext  = new DefaultHttpContext();

        httpContext.Features.Set <IHttpResponseFeature>(new TestResponseFeature());
        httpContext.Request.Body        = new NonSeekableReadStream(contentBytes, allowSyncReads: false);
        httpContext.Request.ContentType = "application/json";

        var formatterContext = CreateInputFormatterContext(typeof(User), httpContext);

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

        // Assert
        Assert.False(result.HasError);

        var userModel = Assert.IsType <User>(result.Model);

        Assert.Equal("Person Name", userModel.Name);
        Assert.Equal(30, userModel.Age);
    }
コード例 #5
0
    public async Task Version_2_1_Constructor_SuppressInputFormatterBufferingSetToTrue_UsingMutatedOptions()
    {
        // Arrange
        var mvcOptions = new MvcOptions()
        {
            SuppressInputFormatterBuffering = false,
        };
        var formatter = new NewtonsoftJsonInputFormatter(
            GetLogger(),
            _serializerSettings,
            ArrayPool <char> .Shared,
            _objectPoolProvider,
            mvcOptions,
            new MvcNewtonsoftJsonOptions());

        var content      = "{name: 'Person Name', Age: '30'}";
        var contentBytes = Encoding.UTF8.GetBytes(content);
        var httpContext  = new DefaultHttpContext();

        httpContext.Features.Set <IHttpResponseFeature>(new TestResponseFeature());
        httpContext.Request.Body        = new NonSeekableReadStream(contentBytes);
        httpContext.Request.ContentType = "application/json";

        var formatterContext = CreateInputFormatterContext(typeof(User), httpContext);

        // Act
        // Mutate options after passing into the constructor to make sure that the value type is not store in the constructor
        mvcOptions.SuppressInputFormatterBuffering = true;
        var result = await formatter.ReadAsync(formatterContext);

        // Assert
        Assert.False(result.HasError);

        var userModel = Assert.IsType <User>(result.Model);

        Assert.Equal("Person Name", userModel.Name);
        Assert.Equal(30, userModel.Age);

        Assert.False(httpContext.Request.Body.CanSeek);
        result = await formatter.ReadAsync(formatterContext);

        // Assert
        Assert.False(result.HasError);
        Assert.Null(result.Model);
    }
コード例 #6
0
    public async Task ReadAsync_WithReadJsonWithRequestCulture_DeserializesUsingRequestCulture(
        string dateString,
        string culture)
    {
        // Arrange
        var formatter = new NewtonsoftJsonInputFormatter(
            GetLogger(),
            _serializerSettings,
            ArrayPool <char> .Shared,
            _objectPoolProvider,
            new MvcOptions(),
            new MvcNewtonsoftJsonOptions()
        {
            ReadJsonWithRequestCulture = true
        });

        var originalCulture = CultureInfo.CurrentCulture;

        CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo(culture);

        try
        {
            var content      = $"{{'DateValue': '{dateString}'}}";
            var contentBytes = Encoding.UTF8.GetBytes(content);
            var httpContext  = new DefaultHttpContext();
            httpContext.Features.Set <IHttpResponseFeature>(new TestResponseFeature());
            httpContext.Request.Body        = new NonSeekableReadStream(contentBytes, allowSyncReads: false);
            httpContext.Request.ContentType = "application/json";

            var formatterContext = CreateInputFormatterContext(typeof(TypeWithPrimitives), httpContext);

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

            // Assert
            Assert.False(result.HasError);

            var userModel = Assert.IsType <TypeWithPrimitives>(result.Model);
            Assert.Equal(new DateTime(2019, 05, 15, 00, 00, 00, DateTimeKind.Unspecified), userModel.DateValue);
        }
        finally
        {
            CultureInfo.CurrentCulture = originalCulture;
        }
    }
コード例 #7
0
    public async Task ReadAsync_AllowUserCodeToHandleDeserializationErrors()
    {
        // Arrange
        var serializerSettings = new JsonSerializerSettings
        {
            Error = (sender, eventArgs) =>
            {
                eventArgs.ErrorContext.Handled = true;
            }
        };
        var formatter = new NewtonsoftJsonInputFormatter(
            GetLogger(),
            serializerSettings,
            ArrayPool <char> .Shared,
            _objectPoolProvider,
            new MvcOptions(),
            new MvcNewtonsoftJsonOptions());

        var content      = $"{{'id': 'should be integer', 'name': 'test location'}}";
        var contentBytes = Encoding.UTF8.GetBytes(content);
        var httpContext  = new DefaultHttpContext();

        httpContext.Features.Set <IHttpResponseFeature>(new TestResponseFeature());
        httpContext.Request.Body        = new NonSeekableReadStream(contentBytes, allowSyncReads: false);
        httpContext.Request.ContentType = "application/json";

        var formatterContext = CreateInputFormatterContext(typeof(Location), httpContext);

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

        // Assert
        Assert.False(result.HasError);
        var location = (Location)result.Model;

        Assert.Equal(0, location?.Id);
        Assert.Equal("test location", location?.Name);
    }