Exemplo n.º 1
0
        public void CreateRequestModel_should_create_a_command_request_model_from_the_http_request_body()
        {
            // Given an HttpRequest with a json message in the body
            HttpContext httpContext = new DefaultHttpContext();

            httpContext.Request.Method      = "POST";
            httpContext.Request.ContentType = "application/json";
            httpContext.Request.Body        = new MemoryStream(Encoding.UTF8.GetBytes("{ name: 'Bar', ranking: 10 }"));

            // Plus some empty route data
            RouteData routeData = new RouteData();

            // When I try to bind to a request model
            IInputFormatter            inputFormatter = new JsonInputFormatter();
            IEnumerable <IValueParser> valueParsers   = new List <IValueParser> {
                new RouteValueParser(routeData)
            };
            RequestModelActivator modelActivator = new RequestModelActivator(httpContext, inputFormatter, valueParsers);
            var requestModel = modelActivator.CreateRequestModelAsync <Foo>().Result;

            // Then the result should be an instance of Foo with all of it's properties set correctly
            Foo result = requestModel;

            Assert.Equal("Bar", result?.Name);
            Assert.Equal(10, result?.Ranking);
        }
Exemplo n.º 2
0
        public void CreateRequestModel_should_merge_message_body_and_route_data_to_create_a_command_request_model()
        {
            // Given an HttpRequest with a json message in the body
            HttpContext httpContext = new DefaultHttpContext();

            httpContext.Request.Method      = "POST";
            httpContext.Request.ContentType = "application/json";
            httpContext.Request.Body        = new MemoryStream(Encoding.UTF8.GetBytes("{ name: 'Bar', ranking: 10 }"));

            // Plus some route data
            RouteData routeData = new RouteData();

            routeData.Values.Add("Ranking", "42");

            // When I try to bind to a request model
            IInputFormatter            inputFormatter = new JsonInputFormatter();
            IEnumerable <IValueParser> valueParsers   = new List <IValueParser> {
                new RouteValueParser(routeData)
            };
            RequestModelActivator modelActivator = new RequestModelActivator(httpContext, inputFormatter, valueParsers);
            var requestModel = modelActivator.CreateRequestModelAsync <Foo>().Result;

            // Then the result should be an instance of Foo with all of it's properties set correctly
            // from a combination of the message body and the route data
            Foo result = requestModel;

            result?.Name.Should().Be("Bar");
            result?.Ranking.Should().Be(42);
        }
Exemplo n.º 3
0
        public void BindRequestParameters_should_create_a_command_request_model_from_parameters_in_route_template()
        {
            // Given an HttpRequest with an empty body
            HttpContext httpContext = new DefaultHttpContext();

            httpContext.Request.Method      = "GET";
            httpContext.Request.ContentType = "application/json";
            httpContext.Request.Body        = new MemoryStream(Encoding.UTF8.GetBytes(""));

            // And some model properties in the route data
            RouteData routeData = new RouteData();

            routeData.Values.Add("name", "Bar");
            routeData.Values.Add("Ranking", "10");

            // When I try to bind to a request model
            IInputFormatter            inputFormatter = new JsonInputFormatter();
            IEnumerable <IValueParser> valueParsers   = new List <IValueParser> {
                new RouteValueParser(routeData)
            };
            RequestModelActivator modelActivator = new RequestModelActivator(httpContext, inputFormatter, valueParsers);
            var requestModel = modelActivator.CreateRequestModelAsync <Foo>().Result;

            // Then the result should be an instance of Foo with all of it's properties set correctly
            Foo result = requestModel;

            Assert.Equal("Bar", result?.Name);
            Assert.Equal(10, result?.Ranking);
        }
Exemplo n.º 4
0
        public async Task RouteAsync(RouteContext context)
        {
            // Build a request model from the request
            IInputFormatter            inputFormatter = new JsonInputFormatter();
            IEnumerable <IValueParser> valueParsers   = new List <IValueParser> {
                new RouteValueParser(context.RouteData)
            };
            RequestModelActivator modelActivator = new RequestModelActivator(
                context.HttpContext,
                inputFormatter,
                valueParsers
                );
            TRequest requestModel = await modelActivator.CreateRequestModelAsync <TRequest>();

            // Run the request through our command pipeline
            IHandlerResult pipelineResult = _pipeline.Dispatch(context.HttpContext, requestModel);

            // If the request was handled by our pipeline then write the response out
            if (pipelineResult.IsHandled)
            {
                // Serialize the response model
                IOutputFormatter outputFormatter = new JsonOutputFormatter();
                ResponseWriter   responseWriter  = new ResponseWriter(context.HttpContext, outputFormatter);
                await responseWriter.SerializeResponseAsync(pipelineResult);

                // Let OWIN know our middleware handled the request
                context.IsHandled = true;
            }
        }
Exemplo n.º 5
0
        public void InputFormatters_InstancesOf_ReturnsNonEmptyCollectionIfSomeExist()
        {
            // Arrange
            var formatters = new MvcOptions().InputFormatters;

            formatters.Add(typeof(JsonInputFormatter));
            var formatter1 = new JsonInputFormatter();
            var formatter2 = Mock.Of <IInputFormatter>();
            var formatter3 = new JsonInputFormatter();
            var formatter4 = Mock.Of <IInputFormatter>();

            formatters.Add(formatter1);
            formatters.Add(formatter2);
            formatters.Add(formatter3);
            formatters.Add(formatter4);

            var expectedFormatters = new List <JsonInputFormatter> {
                formatter1, formatter3
            };

            // Act
            var jsonFormatters = formatters.InstancesOf <JsonInputFormatter>().ToList();

            // Assert
            Assert.NotEmpty(jsonFormatters);
            Assert.Equal(jsonFormatters, expectedFormatters);
        }
        public static void AddEmptyContentTypeFormatter(this MvcOptions options)
        {
            _ = options ?? throw new ArgumentNullException(nameof(options));

            JsonInputFormatter formatter = (JsonInputFormatter)options.InputFormatters.First(f => f.GetType() == typeof(JsonInputFormatter));

            options.InputFormatters.Add(new EmptyContentTypeJsonInputFormatter(formatter));
        }
    public MyModelBinder(IHttpRequestStreamReaderFactory readerFactory, ILoggerFactory loggerFactory, IOptions <MvcOptions> options, IOptions <MvcJsonOptions> jsonOptions, ArrayPool <char> charPool, ObjectPoolProvider objectPoolProvider)
    {
        var formatters         = options.Value.InputFormatters.ToList();
        int jsonFormatterIndex = formatters.FirstIndexOf(formatter => formatter is JsonInputFormatter);
        JsonSerializerSettings myCustomSettings = ...
                                                  formatters[jsonFormatterIndex] = new JsonInputFormatter(loggerFactory.CreateLogger("MyCustomJsonFormatter"), myCustomSettings, charPool, objectPoolProvider, options.Value, jsonOptions.Value);

        _bodyModelBinder = new BodyModelBinder(formatters, readerFactory, loggerFactory, options.Value);
    }
Exemplo n.º 8
0
        public void Constructor_UsesSerializerSettings()
        {
            // Arrange
            // Act
            var serializerSettings = new JsonSerializerSettings();
            var jsonFormatter = new JsonInputFormatter(serializerSettings);

            // Assert
            Assert.Same(serializerSettings, jsonFormatter.SerializerSettings);
        }
Exemplo n.º 9
0
        public void Constructor_UsesSerializerSettings()
        {
            // Arrange
            // Act
            var serializerSettings = new JsonSerializerSettings();
            var jsonFormatter      = new JsonInputFormatter(serializerSettings);

            // Assert
            Assert.Same(serializerSettings, jsonFormatter.SerializerSettings);
        }
Exemplo n.º 10
0
        public static void UseHtmlEncodeJsonInputFormatter(this MvcOptions opts, ILogger <MvcOptions> logger, ObjectPoolProvider objectPoolProvider)
        {
            opts.InputFormatters.RemoveType <JsonInputFormatter>();
            var serializerSettings = new JsonSerializerSettings
            {
                ContractResolver = new HtmlEncodeContractResolver()
            };
            var jsonInputFormatter = new JsonInputFormatter(logger, serializerSettings, ArrayPool <char> .Shared, objectPoolProvider);

            opts.InputFormatters.Add(jsonInputFormatter);
        }
Exemplo n.º 11
0
        public void DefaultMediaType_ReturnsApplicationJson()
        {
            // Arrange
            var formatter = new JsonInputFormatter();

            // Act
            var mediaType = formatter.SupportedMediaTypes[0];

            // Assert
            Assert.Equal("application/json", mediaType.ToString());
        }
Exemplo n.º 12
0
 public ToUppercaseJsonInputFormatter(JsonInputFormatter jsonInputFormatter)
 {
     _jsonInputFormatter = jsonInputFormatter;
     foreach (var supportedEncoding in _jsonInputFormatter.SupportedEncodings)
     {
         SupportedEncodings.Add(supportedEncoding);
     }
     foreach (var supportedMediaType in _jsonInputFormatter.SupportedMediaTypes)
     {
         SupportedMediaTypes.Add(supportedMediaType);
     }
 }
Exemplo n.º 13
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.º 14
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);
        }
        public void InputFormatters_InstanceOf_ReturnsInstanceOfIInputFormatterIfOneExists()
        {
            // Arrange
            var formatters = new MvcOptions().InputFormatters;
            formatters.Add(Mock.Of<IInputFormatter>());
            var jsonFormatter = new JsonInputFormatter();
            formatters.Add(jsonFormatter);
            formatters.Add(typeof(JsonInputFormatter));

            // Act
            var formatter = formatters.InstanceOf<JsonInputFormatter>();

            // Assert
            Assert.NotNull(formatter);
            Assert.IsType<JsonInputFormatter>(formatter);
            Assert.Same(jsonFormatter, formatter);
        }
Exemplo n.º 16
0
        public static IMvcCoreBuilder AddGitLfs(this IMvcCoreBuilder builder)
        {
            builder.AddJsonFormatters();
            builder.AddApplicationPart(typeof(LfsConstants).GetTypeInfo().Assembly);
            builder.AddMvcOptions(options =>
            {
                options.Filters.Add(new ProducesAttribute(LfsConstants.LfsMediaType.MediaType.Buffer));
                options.Filters.Add(new TypeFilterAttribute(typeof(BasicAuthFilter)));

                JsonOutputFormatter jsonOutput = options.OutputFormatters.OfType <JsonOutputFormatter>().First();
                jsonOutput.SupportedMediaTypes.Add(LfsConstants.LfsMediaType);

                JsonInputFormatter jsonInput = options.InputFormatters.OfType <JsonInputFormatter>().First();
                jsonInput.SupportedMediaTypes.Add(LfsConstants.LfsMediaType);
            });
            return(builder);
        }
Exemplo n.º 17
0
        public void InputFormatters_InstanceOfOrDefault_ReturnsInstanceOfIInputFormatterIfOneExists()
        {
            // Arrange
            var formatters = new MvcOptions().InputFormatters;

            formatters.Add(Mock.Of <IInputFormatter>());
            formatters.Add(typeof(JsonInputFormatter));
            var jsonFormatter = new JsonInputFormatter();

            formatters.Add(jsonFormatter);

            // Act
            var formatter = formatters.InstanceOfOrDefault <JsonInputFormatter>();

            // Assert
            Assert.NotNull(formatter);
            Assert.IsType <JsonInputFormatter>(formatter);
            Assert.Same(jsonFormatter, formatter);
        }
Exemplo n.º 18
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.º 19
0
     public void OnResourceExecuting(ResourceExecutingContext context)
     {
         // remove existing input formatter and add a new one
         var camelcaseInputFormatter = new JsonInputFormatter(serializerSettings);
         var inputFormatter = context.InputFormatters.FirstOrDefault(frmtr => frmtr is JsonInputFormatter);
         if (inputFormatter != null)
         {
             context.InputFormatters.Remove(inputFormatter);
             context.InputFormatters.Add(camelcaseInputFormatter);
         }
 
         // remove existing output formatter and add a new one
         var camelcaseOutputFormatter = new JsonOutputFormatter(serializerSettings);
         var outputFormatter = context.OutputFormatters.FirstOrDefault(frmtr => frmtr is JsonOutputFormatter);
         if (outputFormatter != null)
         {
             context.OutputFormatters.Remove(outputFormatter);
             context.OutputFormatters.Add(camelcaseOutputFormatter);
         }
     }
Exemplo n.º 20
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);
        }
Exemplo n.º 21
0
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            var mobileInputFormatter = new JsonInputFormatter(serializerSettings);
            var inputFormatter       = context.InputFormatters.FirstOrDefault(frmtr => frmtr is JsonInputFormatter);

            if (inputFormatter != null)
            {
                context.InputFormatters.Remove(inputFormatter);
            }
            context.InputFormatters.Add(mobileInputFormatter);

            var mobileOutputFormatter = new JsonOutputFormatter(serializerSettings);
            var outputFormatter       = context.OutputFormatters.FirstOrDefault(frmtr => frmtr is JsonOutputFormatter);

            if (outputFormatter != null)
            {
                context.OutputFormatters.Remove(outputFormatter);
            }
            context.OutputFormatters.Add(mobileOutputFormatter);
        }
Exemplo n.º 22
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.Configure <MvcOptions>(options =>
            {
                options.InputFormatters.Clear();

                var jsonInputFormatter = new JsonInputFormatter();
                jsonInputFormatter.SupportedMediaTypes.Clear();
                jsonInputFormatter.SupportedMediaTypes.Add(JsonMediaType);
                options.InputFormatters.Add(jsonInputFormatter);

                var xmlSerializerInputFormatter = new XmlSerializerInputFormatter();
                xmlSerializerInputFormatter.SupportedMediaTypes.Clear();
                xmlSerializerInputFormatter.SupportedMediaTypes.Add(XmlSerializerMediaType);
                options.InputFormatters.Add(xmlSerializerInputFormatter);

                var xmlDataContractSerializerInputFormatter = new XmlDataContractSerializerInputFormatter();
                xmlDataContractSerializerInputFormatter.SupportedMediaTypes.Clear();
                xmlDataContractSerializerInputFormatter.SupportedMediaTypes.Add(XmlDataContractSerializerMediaType);
                options.InputFormatters.Add(xmlDataContractSerializerInputFormatter);

                options.OutputFormatters.Clear();

                var jsonOutputFormatter = new JsonOutputFormatter();
                jsonOutputFormatter.SupportedMediaTypes.Clear();
                jsonOutputFormatter.SupportedMediaTypes.Add(JsonMediaType);
                options.OutputFormatters.Add(jsonOutputFormatter);

                var xmlSerializerOutputFormatter = new XmlSerializerOutputFormatter();
                xmlSerializerOutputFormatter.SupportedMediaTypes.Clear();
                xmlSerializerOutputFormatter.SupportedMediaTypes.Add(XmlSerializerMediaType);
                options.OutputFormatters.Add(xmlSerializerOutputFormatter);

                var xmlDataContractSerializerOutputFormatter = new XmlDataContractSerializerOutputFormatter();
                xmlDataContractSerializerOutputFormatter.SupportedMediaTypes.Clear();
                xmlDataContractSerializerOutputFormatter.SupportedMediaTypes.Add(XmlDataContractSerializerMediaType);
                options.OutputFormatters.Add(xmlDataContractSerializerOutputFormatter);
            });
        }
Exemplo n.º 23
0
        private static void SetupMvcOptions(MvcOptions setupAction)
        {
            setupAction.ReturnHttpNotAcceptable = true;
            setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());

            XmlDataContractSerializerInputFormatter xmlDataContractSerializerInputFormatter =
                new XmlDataContractSerializerInputFormatter();

            xmlDataContractSerializerInputFormatter.SupportedMediaTypes.Add(
                "application/vnd.marvin.authorwithdateofdeath.full+xml");

            setupAction.InputFormatters.Add(xmlDataContractSerializerInputFormatter);

            JsonOutputFormatter jsonOutputFormatter =
                setupAction.OutputFormatters.OfType <JsonOutputFormatter>().FirstOrDefault();

            jsonOutputFormatter?.SupportedMediaTypes.Add(VendorMediaType);

            JsonInputFormatter jsonInputFormatter =
                setupAction.InputFormatters.OfType <JsonInputFormatter>().FirstOrDefault();

            jsonInputFormatter?.SupportedMediaTypes.Add("application/vnd.marvin.author.full+json");
            jsonInputFormatter?.SupportedMediaTypes.Add("application/vnd.marvin.authorwithdateofdeath.full+json");
        }
Exemplo n.º 24
0
        public void CanRead_ReturnsTrueForAnySupportedContentType(string requestContentType, bool expectedCanRead)
        {
            // Arrange
            var loggerMock = GetLogger();

            var formatter = new JsonInputFormatter(loggerMock);
            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);
        }
Exemplo n.º 25
0
        public async Task JsonFormatterReadsComplexTypes()
        {
            // Arrange
            var content = "{name: 'Person Name', Age: '30'}";
            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);

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

            // Assert
            var userModel = Assert.IsType<User>(model);
            Assert.Equal("Person Name", userModel.Name);
            Assert.Equal(30, userModel.Age);
        }
Exemplo n.º 26
0
        public async Task JsonFormatterReadsComplexTypes()
        {
            // Arrange
            var content = "{name: 'Person Name', Age: '30'}";
            var logger = GetLogger();
            var formatter = new JsonInputFormatter(logger);
            var contentBytes = Encoding.UTF8.GetBytes(content);

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

            // 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.º 27
0
        public async Task ReadAsync_AddsModelValidationErrorsToModelState()
        {
            // Arrange
            var content = "{name: 'Person Name', Age: 'not-an-age'}";
            var logger = GetLogger();
            var formatter = new JsonInputFormatter(logger);
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(User));
            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.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.º 28
0
 public EmptyContentTypeJsonInputFormatter(JsonInputFormatter inner)
 {
     _inner = inner ?? throw new ArgumentNullException(nameof(inner));
 }
Exemplo n.º 29
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.º 30
0
        public async Task JsonFormatterReadsSimpleTypes(string content, Type type, object expected)
        {
            // Arrange
            var logger = GetLogger();
            var formatter = new JsonInputFormatter(logger);
            var contentBytes = Encoding.UTF8.GetBytes(content);

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

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

            // Assert
            Assert.False(result.HasError);
            Assert.Equal(expected, result.Model);
        }
Exemplo n.º 31
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.º 32
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 actionContext = GetActionContext(contentBytes, "application/json;charset=utf-8");
            var metadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(UserLogin));
            var inputFormatterContext = new InputFormatterContext(actionContext, metadata.ModelType);

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

            // Assert
            Assert.False(actionContext.ModelState.IsValid);

            var modelErrorMessage = actionContext.ModelState.Values.First().Errors[0].Exception.Message;
            Assert.Contains("Required property 'Password' not found in JSON", modelErrorMessage);
        }
Exemplo n.º 33
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);
        }
Exemplo n.º 34
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 actionContext = GetActionContext(contentBytes);
            var metadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(User));
            var context = new InputFormatterContext(actionContext, metadata.ModelType);

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

            // Assert
            Assert.Equal("Could not convert string to decimal: not-an-age. Path 'Age', line 1, position 39.",
                         actionContext.ModelState["Age"].Errors[0].Exception.Message);
        }
Exemplo n.º 35
0
        public async Task ChangesTo_DefaultSerializerSettings_TakesEffect()
        {
            // Arrange
            // missing password property here
            var contentBytes = Encoding.UTF8.GetBytes("{ \"UserName\" : \"John\"}");
            var logger = GetLogger();
            var jsonFormatter = new JsonInputFormatter(logger);
            // by default we ignore missing members, so here explicitly changing it
            jsonFormatter.SerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes, "application/json;charset=utf-8");
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(UserLogin));
            var inputFormatterContext = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                metadata: metadata,
                readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader);

            // 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.º 36
0
        // This method gets called by a runtime.
        // Use this method to add services to the container
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging();

            services.Configure<MvcOptions>(options =>
            {

                var settings = new JsonSerializerSettings()
                {
                    Formatting = Formatting.Indented,
                    NullValueHandling = NullValueHandling.Ignore,
                    ContractResolver = new CamelCaseExceptDictionaryKeysResolver()
                };

                options.InputFormatters.Clear();
                options.OutputFormatters.Clear();

                var inputFormatter = new JsonInputFormatter(settings);
                var outputFormatter = new JsonOutputFormatter(settings);

                options.InputFormatters.Insert(0, inputFormatter);
                options.OutputFormatters.Insert(0, outputFormatter);

                options.ModelBinders.Add(new UserPrincipleModelBinder());

                options.Filters.Add(new AuthenticationFilterAttribute() { DataProvider = DataAccessControllerFactory.Provider });
                options.Filters.Add(new HandleFinalErrorFilterAttribute());
            });

            services.AddSingleton<IControllerFactory, DataAccessControllerFactory>();
            services.AddMvc();
        }
Exemplo n.º 37
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.º 38
0
        public async Task ThrowsException_OnSupplyingNull_ForRequiredValueType()
        {
            // Arrange
            var contentBytes = Encoding.UTF8.GetBytes("{\"Id\":\"null\",\"Name\":\"Programming C#\"}");
            var jsonFormatter = new JsonInputFormatter();
            var actionContext = GetActionContext(contentBytes, "application/json;charset=utf-8");
            var metadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(Book));
            var inputFormatterContext = new InputFormatterContext(actionContext, metadata.ModelType);

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

            // Assert
            var book = obj as Book;
            Assert.NotNull(book);
            Assert.Equal(0, book.Id);
            Assert.Equal("Programming C#", book.Name);
            Assert.False(actionContext.ModelState.IsValid);

            Assert.Equal(1, actionContext.ModelState.Values.First().Errors.Count);
            var modelErrorMessage = actionContext.ModelState.Values.First().Errors[0].Exception.Message;
            Assert.Contains("Could not convert string to integer: null. Path 'Id'", modelErrorMessage);
        }
Exemplo n.º 39
0
        public async Task ReadAsync_InvalidArray_AddsOverflowErrorsToModelState()
        {
            // Arrange
            var content = "[0, 23, 300]";
            var formatter = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(byte[]));
            var context = new InputFormatterContext(
                httpContext,
                modelName: string.Empty,
                modelState: modelState,
                metadata: metadata);

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

            // Assert
            Assert.True(result.HasError);
            Assert.Equal("The supplied value is invalid for Byte.", modelState["[2]"].Errors[0].ErrorMessage);
            Assert.Null(modelState["[2]"].Errors[0].Exception);
        }
Exemplo n.º 40
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.º 41
0
        public async Task Validates_RequiredAttribute_OnRegularAndInheritedProperties(Type type)
        {
            // Arrange
            var contentBytes = Encoding.UTF8.GetBytes("{ \"Name\" : \"Programming C#\"}");
            var jsonFormatter = new JsonInputFormatter();
            var actionContext = GetActionContext(contentBytes, "application/json;charset=utf-8");
            var metadata = new EmptyModelMetadataProvider().GetMetadataForType(type);
            var inputFormatterContext = new InputFormatterContext(actionContext, metadata.ModelType);

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

            // Assert
            Assert.False(actionContext.ModelState.IsValid);
            Assert.Equal(1, actionContext.ModelState.Count);

            var modelErrorMessage = actionContext.ModelState.Values.First().Errors[0].Exception.Message;
            Assert.Contains("Required property 'Id' not found in JSON", modelErrorMessage);
        }
Exemplo n.º 42
0
        public void Creates_SerializerSettings_ByDefault()
        {
            // Arrange
            // Act
            var jsonFormatter = new JsonInputFormatter();

            // Assert
            Assert.NotNull(jsonFormatter.SerializerSettings);
        }
Exemplo n.º 43
0
        public async Task Validates_RequiredAttributeOnStructTypes()
        {
            // Arrange
            var contentBytes = Encoding.UTF8.GetBytes("{\"Longitude\":{}}");
            var jsonFormatter = new JsonInputFormatter();
            var actionContext = GetActionContext(contentBytes, "application/json;charset=utf-8");
            var metadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(GpsCoordinate));
            var inputFormatterContext = new InputFormatterContext(actionContext, metadata.ModelType);

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

            // Assert
            Assert.False(actionContext.ModelState.IsValid);
            Assert.Equal(2, actionContext.ModelState.Count);
            var errorMessages = GetModelStateErrorMessages(actionContext.ModelState);
            Assert.Equal(3, errorMessages.Count());
            Assert.Contains(
                errorMessages,
                (errorMessage) => errorMessage.Contains("Required property 'Latitude' not found in JSON"));
            Assert.Contains(
                errorMessages,
                (errorMessage) => errorMessage.Contains("Required property 'X' not found in JSON"));
            Assert.Contains(
                errorMessages,
                (errorMessage) => errorMessage.Contains("Required property 'Y' not found in JSON"));
        }
Exemplo n.º 44
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {


            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                        builder =>
                        {
                            builder.AllowCredentials();
                            builder.AllowAnyOrigin();
                            builder.AllowAnyHeader();
                            builder.AllowAnyMethod();
                            builder.Build();
                        });
            });

            services.AddEntityFramework()
               .AddInMemoryDatabase()
               .AddDbContext<ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>>(options =>
               {
                   options.UseInMemoryDatabase();
               });
            services.AddScoped<IAuthStore<ApplicationUser, Application>, AuthStore<ApplicationUser, Application, IdentityRole,
                ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>, string>>();
            services.AddScoped<AuthManager<ApplicationUser, Application>>();

            //var i = new MockUnitOfWork<string, ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>>(null);
            //IUnitOfWork
            services.AddScoped<IUnitOfWork<string>, MockUnitOfWork<string, ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>>>();

            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.Password = new PasswordOptions()
                {
                    RequiredLength = 1,
                    RequireDigit = false,
                    RequireLowercase = false,
                    RequireUppercase = false,
                    RequireNonLetterOrDigit = false

                };
            }).AddEntityFrameworkStores<ApplicationDbContext<ApplicationUser, Application, IdentityRole, string>>().AddDefaultTokenProviders();
            services.AddAuthentication();
            services.AddAuthorization(options => options.AddPolicy("ElevatedRights", policy =>
                   policy.RequireRole("Admin", "PowerUser", "BackupAdministrator").Build()));

            // Add framework services.
            services.AddInstance<IConfiguration>(Configuration);
            services.AddCaching();
            services.AddSignalR();
            services.AddMvc(options =>
            {
                // for CEf client
                var jsonOutputFormatter = new JsonOutputFormatter();
                jsonOutputFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects;

                var jsonInputFormatter = new JsonInputFormatter();
                jsonInputFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Objects;

                options.OutputFormatters.Insert(0, jsonOutputFormatter);
                options.InputFormatters.Insert(0, jsonInputFormatter);
            });
        }
Exemplo n.º 45
0
        public async Task Validation_DoesNotHappen_ForNonRequired_ValueTypeProperties()
        {
            // Arrange
            var contentBytes = Encoding.UTF8.GetBytes("{\"Name\":\"Seattle\"}");
            var jsonFormatter = new JsonInputFormatter();
            var actionContext = GetActionContext(contentBytes, "application/json;charset=utf-8");
            var metadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(Location));
            var inputFormatterContext = new InputFormatterContext(actionContext, metadata.ModelType);

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

            // Assert
            Assert.True(actionContext.ModelState.IsValid);
            var location = obj as Location;
            Assert.NotNull(location);
            Assert.Equal(0, location.Id);
            Assert.Equal("Seattle", location.Name);
        }
Exemplo n.º 46
0
        public async Task ReadAsync_InvalidComplexArray_AddsOverflowErrorsToModelState()
        {
            // Arrange
            var content = "[{name: 'Name One', Age: 30}, {name: 'Name Two', Small: 300}]";
            var formatter = new JsonInputFormatter();
            var contentBytes = Encoding.UTF8.GetBytes(content);

            var modelState = new ModelStateDictionary();
            var httpContext = GetHttpContext(contentBytes);
            var provider = new EmptyModelMetadataProvider();
            var metadata = provider.GetMetadataForType(typeof(User[]));
            var context = new InputFormatterContext(
                httpContext,
                modelName: "names",
                modelState: modelState,
                metadata: metadata);

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

            // Assert
            Assert.True(result.HasError);
            Assert.Equal(
                "Error converting value 300 to type 'System.Byte'. Path '[1].Small', line 1, position 59.",
                modelState["names[1].Small"].Errors[0].Exception.Message);
        }
Exemplo n.º 47
0
        public async Task Validation_DoesNotHappen_OnNullableValueTypeProperties()
        {
            // Arrange
            var contentBytes = Encoding.UTF8.GetBytes("{}");
            var jsonFormatter = new JsonInputFormatter();
            var actionContext = GetActionContext(contentBytes, "application/json;charset=utf-8");
            var metadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(Venue));
            var inputFormatterContext = new InputFormatterContext(actionContext, metadata.ModelType);

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

            // Assert
            Assert.True(actionContext.ModelState.IsValid);
            var venue = obj as Venue;
            Assert.NotNull(venue);
            Assert.Null(venue.Location);
            Assert.Null(venue.NearByLocations);
            Assert.Null(venue.Name);
        }