コード例 #1
0
        public async Task ModelBinder_ReturnsNoResult_IfBinderMatchesButDoesNotSetModel()
        {
            // Arrange
            var bindingContext = new ModelBindingContext
            {
                FallbackToEmptyPrefix   = true,
                ModelMetadata           = new EmptyModelMetadataProvider().GetMetadataForType(typeof(List <int>)),
                ModelName               = "someName",
                ModelState              = new ModelStateDictionary(),
                OperationBindingContext = new OperationBindingContext(),
                ValueProvider           = new SimpleValueProvider
                {
                    { "someOtherName", "dummyValue" }
                },
            };

            var modelBinder = new Mock <IModelBinder>();

            modelBinder
            .Setup(mb => mb.BindModelAsync(It.IsAny <ModelBindingContext>()))
            .Returns(ModelBindingResult.FailedAsync("someName"));

            var composite = CreateCompositeBinder(modelBinder.Object);

            // Act
            var result = await composite.BindModelAsync(bindingContext);

            // Assert
            Assert.Equal(ModelBindingResult.NoResult, result);
        }
コード例 #2
0
        public async Task ModelBinder_DoesNotFallBackToEmpty_IfErrorsAreAdded()
        {
            // Arrange
            var bindingContext = new ModelBindingContext
            {
                FallbackToEmptyPrefix   = false,
                ModelMetadata           = new EmptyModelMetadataProvider().GetMetadataForType(typeof(List <int>)),
                ModelName               = "someName",
                ModelState              = new ModelStateDictionary(),
                OperationBindingContext = new OperationBindingContext(),
                ValueProvider           = new SimpleValueProvider
                {
                    { "someOtherName", "dummyValue" }
                },
            };

            var modelBinder = new Mock <IModelBinder>();

            modelBinder
            .Setup(mb => mb.BindModelAsync(It.IsAny <ModelBindingContext>()))
            .Callback <ModelBindingContext>(context =>
            {
                Assert.Equal("someName", context.ModelName);
                context.ModelState.AddModelError(context.ModelName, "this is an error message");
            })
            .Returns(ModelBindingResult.FailedAsync("someName"))
            .Verifiable();

            var composite = CreateCompositeBinder(modelBinder.Object);

            // Act & Assert
            var result = await composite.BindModelAsync(bindingContext);

            modelBinder.Verify(mb => mb.BindModelAsync(It.IsAny <ModelBindingContext>()), Times.Once);
        }
コード例 #3
0
        public async Task BindActionArgumentsAsync_DoesNotAddActionArguments_IfBinderDoesNotSetModel()
        {
            // Arrange
            var actionDescriptor = GetActionDescriptor();

            actionDescriptor.Parameters.Add(
                new ParameterDescriptor
            {
                Name          = "foo",
                ParameterType = typeof(object),
                BindingInfo   = new BindingInfo(),
            });

            var binder = new Mock <IModelBinder>();

            binder
            .Setup(b => b.BindModelAsync(It.IsAny <ModelBindingContext>()))
            .Returns(ModelBindingResult.FailedAsync(string.Empty));

            var controllerContext = GetControllerContext(actionDescriptor);

            controllerContext.ModelBinders.Add(binder.Object);
            controllerContext.ValueProviders.Add(new SimpleValueProvider());

            var argumentBinder        = GetArgumentBinder();
            var modelMetadataProvider = TestModelMetadataProvider.CreateDefaultProvider();

            // Act
            var result = await argumentBinder
                         .BindActionArgumentsAsync(controllerContext, new TestController());

            // Assert
            Assert.Empty(result);
        }
コード例 #4
0
        private static IModelBinder CreateIntBinder()
        {
            Mock <IModelBinder> mockIntBinder = new Mock <IModelBinder>();

            mockIntBinder
            .Setup(o => o.BindModelAsync(It.IsAny <ModelBindingContext>()))
            .Returns((ModelBindingContext mbc) =>
            {
                var value = mbc.ValueProvider.GetValue(mbc.ModelName);
                if (value == ValueProviderResult.None)
                {
                    return(ModelBindingResult.NoResultAsync);
                }

                var model = value.ConvertTo(mbc.ModelType);
                if (model == null)
                {
                    return(ModelBindingResult.FailedAsync(mbc.ModelName));
                }
                else
                {
                    return(ModelBindingResult.SuccessAsync(mbc.ModelName, model));
                }
            });
            return(mockIntBinder.Object);
        }
コード例 #5
0
        public async Task FailedAsync_SetsProperties()
        {
            // Arrange
            var key = "someName";

            // Act
            var result = await ModelBindingResult.FailedAsync(key);

            // Assert
            Assert.Same(key, result.Key);
            Assert.False(result.IsModelSet);
            Assert.Null(result.Model);
        }
コード例 #6
0
            public Task <ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
            {
                if (typeof(OrderStatus).IsAssignableFrom(bindingContext.ModelType))
                {
                    var request = bindingContext.OperationBindingContext.HttpContext.Request;

                    // Doing something slightly different here to make sure we don't get accidentally bound
                    // by the type converter binder.
                    OrderStatus model;
                    if (Enum.TryParse <OrderStatus>("Status" + request.Query["status"], out model))
                    {
                        return(ModelBindingResult.SuccessAsync("status", model));
                    }

                    return(ModelBindingResult.FailedAsync("status"));
                }

                return(ModelBindingResult.NoResultAsync);
            }
コード例 #7
0
        public async Task BindModel_DoesNotAddAValidationNode_IfModelIsNotSet()
        {
            // Arrange
            var valueProvider = new SimpleValueProvider();
            var mockBinder    = new Mock <IModelBinder>();

            mockBinder
            .Setup(o => o.BindModelAsync(It.IsAny <ModelBindingContext>()))
            .Returns((ModelBindingContext context) =>
            {
                return(ModelBindingResult.FailedAsync("someName"));
            });

            var binder         = CreateCompositeBinder(mockBinder.Object);
            var bindingContext = CreateBindingContext(binder, valueProvider, typeof(SimplePropertiesModel));

            // Act
            var result = await binder.BindModelAsync(bindingContext);

            // Assert
            Assert.Equal(ModelBindingResult.NoResult, result);
        }
コード例 #8
0
        public Task <ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
        {
            var allowedBindingSource = bindingContext.BindingSource;

            if (allowedBindingSource == null ||
                !allowedBindingSource.CanAcceptDataFrom(FromTestAttribute.TestBindingSource))
            {
                return(ModelBindingResult.NoResultAsync);
            }

            var attributes = ((DefaultModelMetadata)bindingContext.ModelMetadata).Attributes;
            var metadata   = attributes.Attributes.OfType <FromTestAttribute>().First();
            var model      = metadata.Value;

            if (!IsSimpleType(bindingContext.ModelType))
            {
                model = Activator.CreateInstance(bindingContext.ModelType);
                return(ModelBindingResult.SuccessAsync(bindingContext.ModelName, model));
            }

            return(ModelBindingResult.FailedAsync(bindingContext.ModelName));
        }
コード例 #9
0
        public async Task BindActionArgumentsAsync_SetsMultipleControllerProperties()
        {
            // Arrange
            var boundPropertyTypes = new Dictionary <string, Type>
            {
                { nameof(TestController.ArrayProperty), typeof(string[]) },                // Skipped
                { nameof(TestController.CollectionProperty), typeof(List <string>) },
                { nameof(TestController.NonCollectionProperty), typeof(Person) },          // Skipped
                { nameof(TestController.NullCollectionProperty), typeof(List <string>) },  // Skipped
                { nameof(TestController.StringProperty), typeof(string) },
            };
            var inputPropertyValues = new Dictionary <string, object>
            {
                { nameof(TestController.ArrayProperty), new string[] { "hello", "world" } },
                { nameof(TestController.CollectionProperty), new List <string> {
                      "hello", "world"
                  } },
                { nameof(TestController.NonCollectionProperty), new Person {
                      Name = "Fred"
                  } },
                { nameof(TestController.NullCollectionProperty), new List <string> {
                      "hello", "world"
                  } },
                { nameof(TestController.StringProperty), "Hello" },
            };
            var expectedPropertyValues = new Dictionary <string, object>
            {
                { nameof(TestController.ArrayProperty), new string[] { "goodbye" } },
                { nameof(TestController.CollectionProperty), new List <string> {
                      "hello", "world"
                  } },
                { nameof(TestController.NonCollectionProperty), new Person {
                      Name = "Ginger"
                  } },
                { nameof(TestController.NullCollectionProperty), null },
                { nameof(TestController.StringProperty), "Hello" },
            };

            var actionDescriptor = GetActionDescriptor();

            foreach (var keyValuePair in boundPropertyTypes)
            {
                actionDescriptor.BoundProperties.Add(
                    new ParameterDescriptor
                {
                    Name          = keyValuePair.Key,
                    BindingInfo   = new BindingInfo(),
                    ParameterType = keyValuePair.Value,
                });
            }

            var controllerContext = GetControllerContext(actionDescriptor);
            var argumentBinder    = GetArgumentBinder();
            var controller        = new TestController();

            var binder = new Mock <IModelBinder>();

            binder
            .Setup(b => b.BindModelAsync(It.IsAny <ModelBindingContext>()))
            .Returns <ModelBindingContext>(bindingContext =>
            {
                // BindingContext.ModelName will be string.Empty here. This is a 'fallback to empty prefix'
                // because the value providers have no data.
                object model;
                if (inputPropertyValues.TryGetValue(bindingContext.FieldName, out model))
                {
                    return(ModelBindingResult.SuccessAsync(bindingContext.ModelName, model));
                }
                else
                {
                    return(ModelBindingResult.FailedAsync(bindingContext.ModelName));
                }
            });
            controllerContext.ModelBinders.Add(binder.Object);
            controllerContext.ValueProviders.Add(new SimpleValueProvider());

            // Act
            var result = await argumentBinder.BindActionArgumentsAsync(controllerContext, controller);

            // Assert
            Assert.Equal(new string[] { "goodbye" }, controller.ArrayProperty);                 // Skipped
            Assert.Equal(new List <string> {
                "hello", "world"
            }, controller.CollectionProperty);
            Assert.Equal(new Person {
                Name = "Ginger"
            }, controller.NonCollectionProperty);                                               // Skipped
            Assert.Null(controller.NullCollectionProperty);                                     // Skipped
            Assert.Null(controller.UntouchedProperty);                                          // Not bound
            Assert.Equal("Hello", controller.StringProperty);
        }
コード例 #10
0
 public Task <ModelBindingResult> BindModelAsync(ModelBindingContext bindingContext)
 {
     return(ModelBindingResult.FailedAsync(bindingContext.ModelName));
 }