public static IModelMetadataProvider CreateDefaultProvider(IList <IMetadataDetailsProvider> providers)
    {
        var detailsProviders = new List <IMetadataDetailsProvider>()
        {
            new DefaultBindingMetadataProvider(),
            new DefaultValidationMetadataProvider(),
            new DataAnnotationsMetadataProvider(
                new MvcOptions(),
                Options.Create(new MvcDataAnnotationsLocalizationOptions()),
                stringLocalizerFactory: null),
            new DataMemberRequiredBindingMetadataProvider(),
        };

        MvcCoreMvcOptionsSetup.ConfigureAdditionalModelMetadataDetailsProviders(detailsProviders);

        detailsProviders.AddRange(providers);

        var validationProviders = TestModelValidatorProvider.CreateDefaultProvider();

        detailsProviders.Add(new HasValidatorsValidationMetadataProvider(validationProviders.ValidatorProviders));

        var compositeDetailsProvider = new DefaultCompositeMetadataDetailsProvider(detailsProviders);

        return(new DefaultModelMetadataProvider(compositeDetailsProvider, Options.Create(new MvcOptions())));
    }
Beispiel #2
0
        public TestMvcOptions()
        {
            Value = new MvcOptions();
            var optionsSetup = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory());

            optionsSetup.Configure(Value);

            var collection = new ServiceCollection().AddOptions();

            collection.AddSingleton <ICompositeMetadataDetailsProvider, DefaultCompositeMetadataDetailsProvider>();
            collection.AddSingleton <IModelMetadataProvider, DefaultModelMetadataProvider>();
            collection.AddSingleton <IValidationAttributeAdapterProvider, ValidationAttributeAdapterProvider>();
            MvcDataAnnotationsMvcOptionsSetup.ConfigureMvc(
                Value,
                collection.BuildServiceProvider());

            var loggerFactory      = new LoggerFactory();
            var serializerSettings = SerializerSettingsProvider.CreateSerializerSettings();

            MvcJsonMvcOptionsSetup.ConfigureMvc(
                Value,
                serializerSettings,
                loggerFactory,
                ArrayPool <char> .Shared,
                new DefaultObjectPoolProvider());
        }
Beispiel #3
0
 public TestMvcOptions()
 {
     Options = new MvcOptions();
     MvcCoreMvcOptionsSetup.ConfigureMvc(Options);
     MvcDataAnnotationsMvcOptionsSetup.ConfigureMvc(Options);
     MvcJsonMvcOptionsSetup.ConfigureMvc(Options, SerializerSettingsProvider.CreateSerializerSettings());
 }
Beispiel #4
0
        public async Task BindParameter_WithTypeProperty_IsBound()
        {
            // Arrange
            var options             = new MvcOptions();
            var modelBinderProvider = new TypeModelBinderProvider();

            // Adding a custom model binder for Type to ensure it doesn't get called
            options.ModelBinderProviders.Insert(0, modelBinderProvider);

            var setup = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory());

            setup.Configure(options);

            // Remove the ExcludeBindingMetadataProvider
            for (var i = options.ModelMetadataDetailsProviders.Count - 1; i >= 0; i--)
            {
                if (options.ModelMetadataDetailsProviders[i] is ExcludeBindingMetadataProvider)
                {
                    options.ModelMetadataDetailsProviders.RemoveAt(i);
                }
            }

            var metadataProvider = TestModelMetadataProvider.CreateProvider(options.ModelMetadataDetailsProviders);
            var testContext      = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.Form = new FormCollection(new Dictionary <string, StringValues>
                {
                    { "name", new[] { "Fred" } },
                    { "type", new[] { "SomeType" } },
                });
            },
                metadataProvider: metadataProvider,
                mvcOptions: options);

            var parameterBinder = ModelBindingTestHelper.GetParameterBinder(testContext.HttpContext.RequestServices);
            var parameter       = new ParameterDescriptor()
            {
                Name          = "Parameter1",
                BindingInfo   = new BindingInfo(),
                ParameterType = typeof(TypesBundle),
            };

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var boundPerson = Assert.IsType <TypesBundle>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);
            Assert.Equal("Fred", boundPerson.Name);

            // The TypeModelBinder should be called
            Assert.True(modelBinderProvider.Invoked);
        }
        public async Task BindParameter_WithTypeProperty_IsNotBound()
        {
            // Arrange
            var options = new MvcOptions();
            var setup   = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory());

            // Adding a custom model binder for Type to ensure it doesn't get called
            options.ModelBinderProviders.Insert(0, new TypeModelBinderProvider());

            setup.Configure(options);

            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder(options);
            var parameter      = new ParameterDescriptor()
            {
                Name          = "Parameter1",
                BindingInfo   = new BindingInfo(),
                ParameterType = typeof(TypesBundle),
            };

            var operationContext = ModelBindingTestHelper.GetOperationBindingContext(request =>
            {
                request.Form = new FormCollection(new Dictionary <string, StringValues>
                {
                    { "name", new[] { "Fred" } },
                    { "type", new[] { "SomeType" } },
                    { "typeArray", new[] { "SomeType1", "SomeType2" } },
                    { "typeList", new[] { "SomeType1", "SomeType2" } },
                    { "typeDictionary", new[] { "parameter[0].Key=key", "parameter[0].Value=value" } },
                    { "methodInfo", new[] { "value" } },
                    { "func", new[] { "value" } },
                }
                                                  );
            });

            var modelState = operationContext.ActionContext.ModelState;

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, operationContext) ??
                                     default(ModelBindingResult);

            // Assert
            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var boundPerson = Assert.IsType <TypesBundle>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);
            Assert.Equal("Fred", boundPerson.Name);

            // ModelState

            // The TypeModelBinder should not be called
            Assert.True(modelState.IsValid);
        }
Beispiel #6
0
        public TestMvcOptions()
        {
            Value = new MvcOptions();
            MvcCoreMvcOptionsSetup.ConfigureMvc(Value);
            var collection = new ServiceCollection().AddOptions();

            MvcDataAnnotationsMvcOptionsSetup.ConfigureMvc(
                Value,
                collection.BuildServiceProvider());
            MvcJsonMvcOptionsSetup.ConfigureMvc(Value, SerializerSettingsProvider.CreateSerializerSettings());
        }
        public async Task BindParameter_WithTypeProperty_IsNotBound()
        {
            // Arrange
            var options = new MvcOptions();
            var setup = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory());

            // Adding a custom model binder for Type to ensure it doesn't get called
            options.ModelBinderProviders.Insert(0, new TypeModelBinderProvider());

            setup.Configure(options);

            var argumentBinder = ModelBindingTestHelper.GetArgumentBinder(options);
            var parameter = new ParameterDescriptor()
            {
                Name = "Parameter1",
                BindingInfo = new BindingInfo(),
                ParameterType = typeof(TypesBundle),
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.Form = new FormCollection(new Dictionary<string, StringValues>
                {
                    { "name", new[] { "Fred" } },
                    { "type", new[] { "SomeType" } },
                    { "typeArray", new[] { "SomeType1", "SomeType2" } },
                    { "typeList", new[] { "SomeType1", "SomeType2" } },
                    { "typeDictionary", new[] { "parameter[0].Key=key", "parameter[0].Value=value" } },
                    { "methodInfo", new[] { "value" } },
                    { "func", new[] { "value" } },
                });
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await argumentBinder.BindModelAsync(parameter, testContext);

            // Assert
            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var boundPerson = Assert.IsType<TypesBundle>(modelBindingResult.Model);
            Assert.NotNull(boundPerson);
            Assert.Equal("Fred", boundPerson.Name);

            // ModelState

            // The TypeModelBinder should not be called
            Assert.True(modelState.IsValid);
        }
        private static DefaultModelBindingContext CreateContext(
            ModelMetadata metadata,
            IValueProvider valueProvider = null,
            bool allowBindingHeaderValuesToNonStringModelTypes = true)
        {
            if (valueProvider == null)
            {
                valueProvider = Mock.Of <IValueProvider>();
            }

            var options = new MvcOptions()
            {
                AllowBindingHeaderValuesToNonStringModelTypes = allowBindingHeaderValuesToNonStringModelTypes
            };
            var setup = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory());

            setup.Configure(options);

            var services = new ServiceCollection();

            services.AddSingleton <ILoggerFactory, NullLoggerFactory>();
            services.AddSingleton(Options.Create(options));
            var serviceProvider = services.BuildServiceProvider();

            var headerName = "Header";

            return(new DefaultModelBindingContext()
            {
                IsTopLevelObject = true,
                ModelMetadata = metadata,
                BinderModelName = metadata.BinderModelName,
                BindingSource = metadata.BindingSource,

                // HeaderModelBinder must always use the field name when getting the values from header value provider
                // but add keys into ModelState using the ModelName. This is for back compat reasons.
                ModelName = $"somePrefix.{headerName}",
                FieldName = headerName,

                ValueProvider = valueProvider,
                ModelState = new ModelStateDictionary(),
                ActionContext = new ActionContext()
                {
                    HttpContext = new DefaultHttpContext()
                    {
                        RequestServices = serviceProvider
                    }
                },
            });
        }
Beispiel #9
0
        // Creates a provider with all the defaults - includes data annotations
        public static ModelMetadataProvider CreateDefaultProvider(IStringLocalizerFactory stringLocalizerFactory = null)
        {
            var detailsProviders = new List <IMetadataDetailsProvider>
            {
                new DefaultBindingMetadataProvider(),
                new DefaultValidationMetadataProvider(),
                CreateDefaultDataAnnotationsProvider(stringLocalizerFactory),
                new DataMemberRequiredBindingMetadataProvider(),
            };

            MvcCoreMvcOptionsSetup.ConfigureAdditionalModelMetadataDetailsProviders(detailsProviders);

            var compositeDetailsProvider = new DefaultCompositeMetadataDetailsProvider(detailsProviders);

            return(new DefaultModelMetadataProvider(compositeDetailsProvider, Options.Create(new MvcOptions())));
        }
        public async Task BindParameter_WithCancellationToken_BindingSourceSpecial()
        {
            // Arrange
            var options = new MvcOptions();
            var setup   = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory());

            options.ModelBinderProviders.Insert(0, new CancellationTokenModelBinderProvider());

            setup.Configure(options);

            var parameterBinder = ModelBindingTestHelper.GetParameterBinder(options);
            var parameter       = new ParameterDescriptor()
            {
                Name          = "Parameter1",
                BindingInfo   = new BindingInfo(),
                ParameterType = typeof(CancellationTokenBundle),
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.Form = new FormCollection(new Dictionary <string, StringValues>
                {
                    { "name", new[] { "Fred" } }
                });
            });

            var modelState = testContext.ModelState;
            var token      = testContext.HttpContext.RequestAborted;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var boundPerson = Assert.IsType <CancellationTokenBundle>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);
            Assert.Equal("Fred", boundPerson.Name);
            Assert.Equal(token, boundPerson.Token);

            // ModelState
            Assert.True(modelState.IsValid);
        }
Beispiel #11
0
        public async Task BindParameter_WithTypeProperty_IsNotBound()
        {
            // Arrange
            var options             = new MvcOptions();
            var setup               = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory());
            var modelBinderProvider = new TypeModelBinderProvider();

            // Adding a custom model binder for Type to ensure it doesn't get called
            options.ModelBinderProviders.Insert(0, modelBinderProvider);

            setup.Configure(options);

            var parameterBinder = ModelBindingTestHelper.GetParameterBinder(options);
            var parameter       = new ParameterDescriptor()
            {
                Name          = "Parameter1",
                BindingInfo   = new BindingInfo(),
                ParameterType = typeof(TypesBundle),
            };

            var testContext = ModelBindingTestHelper.GetTestContext(request =>
            {
                request.Form = new FormCollection(new Dictionary <string, StringValues>
                {
                    { "name", new[] { "Fred" } },
                    { "type", new[] { "SomeType" } },
                });
            });

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var boundPerson = Assert.IsType <TypesBundle>(modelBindingResult.Model);

            Assert.NotNull(boundPerson);
            Assert.Equal("Fred", boundPerson.Name);

            // The TypeModelBinder should not be called
            Assert.False(modelBinderProvider.Invoked);
        }
        public async Task BindParameter_WithFormFile_BindingSourceFormFile()
        {
            // Arrange
            var options = new MvcOptions();
            var setup   = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory());

            options.ModelBinderProviders.Insert(0, new FormFileModelBinderProvider());

            setup.Configure(options);

            var parameterBinder = ModelBindingTestHelper.GetParameterBinder(options);
            var parameter       = new ParameterDescriptor()
            {
                Name          = "Parameter1",
                BindingInfo   = new BindingInfo(),
                ParameterType = typeof(FormFileBundle),
            };

            var data        = "Some Data Is Better Than No Data.";
            var testContext = ModelBindingTestHelper.GetTestContext(
                request =>
            {
                request.QueryString = QueryString.Create("Name", "Fred");
                UpdateRequest(request, data, "File");
            });

            var modelState = testContext.ModelState;

            // Act
            var modelBindingResult = await parameterBinder.BindModelAsync(parameter, testContext);

            // Assert
            // ModelBindingResult
            Assert.True(modelBindingResult.IsModelSet);

            // Model
            var boundPerson = Assert.IsType <FormFileBundle>(modelBindingResult.Model);

            Assert.Equal("Fred", boundPerson.Name);
            Assert.Equal("text.txt", boundPerson.File.FileName);

            // ModelState
            Assert.True(modelState.IsValid);
        }
Beispiel #13
0
        public TestMvcOptions()
        {
            Value = new MvcOptions();
            var optionsSetup = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory());

            optionsSetup.Configure(Value);

            var validationAttributeAdapterProvider = new ValidationAttributeAdapterProvider();
            var dataAnnotationLocalizationOptions  = Options.Create(new MvcDataAnnotationsLocalizationOptions());
            var stringLocalizer        = new Mock <IStringLocalizer>();
            var stringLocalizerFactory = new Mock <IStringLocalizerFactory>();

            stringLocalizerFactory
            .Setup(s => s.Create(It.IsAny <Type>()))
            .Returns(stringLocalizer.Object);

            var dataAnnotationOptionsSetup = new MvcDataAnnotationsMvcOptionsSetup(
                validationAttributeAdapterProvider,
                dataAnnotationLocalizationOptions,
                stringLocalizerFactory.Object);

            dataAnnotationOptionsSetup.Configure(Value);

            var loggerFactory      = new LoggerFactory();
            var jsonOptions        = Options.Create(new MvcNewtonsoftJsonOptions());
            var charPool           = ArrayPool <char> .Shared;
            var objectPoolProvider = new DefaultObjectPoolProvider();

            var mvcJsonMvcOptionsSetup = new NewtonsoftJsonMvcOptionsSetup(
                loggerFactory,
                jsonOptions,
                charPool,
                objectPoolProvider);

            mvcJsonMvcOptionsSetup.Configure(Value);
        }
        private static TestableComplexTypeModelBinder CreateBinder(ModelMetadata metadata)
        {
            var options = new TestOptionsManager<MvcOptions>();
            var setup = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory());
            setup.Configure(options.Value);

            var lastIndex = options.Value.ModelBinderProviders.Count - 1;
            Assert.IsType<ComplexTypeModelBinderProvider>(options.Value.ModelBinderProviders[lastIndex]);
            options.Value.ModelBinderProviders.RemoveAt(lastIndex);
            options.Value.ModelBinderProviders.Add(new TestableComplexTypeModelBinderProvider());

            var factory = TestModelBinderFactory.Create(options.Value.ModelBinderProviders.ToArray());
            return (TestableComplexTypeModelBinder)factory.CreateBinder(new ModelBinderFactoryContext()
            {
                Metadata = metadata,
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = metadata.BinderModelName,
                    BinderType = metadata.BinderType,
                    BindingSource = metadata.BindingSource,
                    PropertyFilterProvider = metadata.PropertyFilterProvider,
                },
            });
        }