private static DefaultModelBindingContext GetBindingContext( IModelMetadataProvider metadataProvider, ModelMetadata modelMetadata) { var bindingContext = new DefaultModelBindingContext { ModelMetadata = modelMetadata, ModelName = "modelName", FieldName = "modelName", ModelState = new ModelStateDictionary(), OperationBindingContext = new OperationBindingContext { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext(), }, ModelBinder = new HeaderModelBinder(), MetadataProvider = metadataProvider, }, BinderModelName = modelMetadata.BinderModelName, BindingSource = modelMetadata.BindingSource, }; return(bindingContext); }
public Task BindModelAsync(ModelBindingContext bindingContext) { var modelTypeValue = bindingContext.ValueProvider.GetValue(ModelNames.CreatePropertyModelName(bindingContext.ModelName, "ModelTypeName")); if (modelTypeValue != null && modelTypeValue.FirstValue != null) { Type modelType = Type.GetType(modelTypeValue.FirstValue); if (this.modelBuilderByType.TryGetValue(modelType, out var modelBinder)) { ModelBindingContext innerModelBindingContext = DefaultModelBindingContext.CreateBindingContext( bindingContext.ActionContext, bindingContext.ValueProvider, this.modelMetadataProvider.GetMetadataForType(modelType), null, bindingContext.ModelName); modelBinder.BindModelAsync(innerModelBindingContext); bindingContext.Result = innerModelBindingContext.Result; return(Task.CompletedTask); } } bindingContext.Result = ModelBindingResult.Failed(); return(Task.CompletedTask); }
private static DefaultModelBindingContext GetBindingContext( Type modelType, HttpContext httpContext = null, IModelMetadataProvider metadataProvider = null) { if (httpContext == null) { httpContext = new DefaultHttpContext(); } if (metadataProvider == null) { metadataProvider = new EmptyModelMetadataProvider(); } var bindingContext = new DefaultModelBindingContext { ActionContext = new ActionContext() { HttpContext = httpContext, }, FieldName = "someField", IsTopLevelObject = true, ModelMetadata = metadataProvider.GetMetadataForType(modelType), ModelName = "someName", ValueProvider = Mock.Of <IValueProvider>(), ModelState = new ModelStateDictionary(), BindingSource = BindingSource.Body, }; return(bindingContext); }
private static DefaultModelBindingContext CreateBindingContext( IModelBinder binder, IValueProvider valueProvider, Type type) { var metadataProvider = TestModelMetadataProvider.CreateDefaultProvider(); var bindingContext = new DefaultModelBindingContext { FallbackToEmptyPrefix = true, IsTopLevelObject = true, ModelMetadata = metadataProvider.GetMetadataForType(type), ModelName = "parameter", FieldName = "parameter", ModelState = new ModelStateDictionary(), ValueProvider = valueProvider, OperationBindingContext = new OperationBindingContext { MetadataProvider = metadataProvider, ModelBinder = binder, }, ValidationState = new ValidationStateDictionary(), }; return(bindingContext); }
public async Task ModelBinder_ReturnsNonEmptyResult_SetsNullValue_SetsModelStateKey() { // Arrange var bindingContext = new DefaultModelBindingContext { FallbackToEmptyPrefix = true, ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(List <int>)), ModelName = "someName", ModelState = new ModelStateDictionary(), OperationBindingContext = new OperationBindingContext(), ValueProvider = new SimpleValueProvider { { "someOtherName", "dummyValue" } }, FieldName = "someName", }; var mockIntBinder = new StubModelBinder(context => { context.Result = ModelBindingResult.Success("someName", model: null); }); var composite = CreateCompositeBinder(mockIntBinder); // Act var result = await composite.BindModelResultAsync(bindingContext); // Assert Assert.NotEqual(default(ModelBindingResult), result); Assert.True(result.IsModelSet); Assert.Equal("someName", result.Key); Assert.Null(result.Model); }
public async Task ModelBinder_DoesNotFallBackToEmpty_IfErrorsAreAdded() { // Arrange var bindingContext = new DefaultModelBindingContext { FallbackToEmptyPrefix = false, ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(List <int>)), ModelName = "someName", ModelState = new ModelStateDictionary(), OperationBindingContext = new OperationBindingContext(), ValueProvider = new SimpleValueProvider { { "someOtherName", "dummyValue" } }, FieldName = "someName", }; var mockIntBinder = new StubModelBinder(context => { Assert.Equal("someName", context.ModelName); context.ModelState.AddModelError(context.ModelName, "this is an error message"); context.Result = ModelBindingResult.Failed("someName"); }); var composite = CreateCompositeBinder(mockIntBinder); // Act & Assert var result = await composite.BindModelResultAsync(bindingContext); Assert.Equal(1, mockIntBinder.BindModelCount); }
public void ModelMetadataProvider_UsesPropertyFilterProviderOnType() { // Arrange var type = typeof(User); var provider = CreateProvider(); var context = new DefaultModelBindingContext(); var expected = new[] { "IsAdmin", "UserName" }; // Act var metadata = provider.GetMetadataForType(type); // Assert var propertyFilter = metadata.PropertyFilterProvider.PropertyFilter; var matched = new HashSet <string>(); foreach (var property in metadata.Properties) { if (propertyFilter(property)) { matched.Add(property.PropertyName); } } Assert.Equal <string>(expected, matched); }
private static DefaultModelBindingContext GetModelBindingContext( bool isReadOnly, IDictionary <string, string> values = null) { var metadataProvider = new TestModelMetadataProvider(); metadataProvider .ForProperty <ModelWithIDictionaryProperty>(nameof(ModelWithIDictionaryProperty.DictionaryProperty)) .BindingDetails(bd => bd.IsReadOnly = isReadOnly); var metadata = metadataProvider.GetMetadataForProperty( typeof(ModelWithIDictionaryProperty), nameof(ModelWithIDictionaryProperty.DictionaryProperty)); var valueProvider = new SimpleValueProvider(); foreach (var kvp in values) { valueProvider.Add(kvp.Key, string.Empty); } var bindingContext = new DefaultModelBindingContext { ModelMetadata = metadata, ModelName = "someName", ModelState = new ModelStateDictionary(), ValueProvider = valueProvider, ValidationState = new ValidationStateDictionary(), }; return(bindingContext); }
private static DefaultModelBindingContext GetBindingContext(Type modelType, Type binderType = null) { var metadataProvider = new TestModelMetadataProvider(); metadataProvider.ForType(modelType).BindingDetails(bd => bd.BinderType = binderType); var operationBindingContext = new OperationBindingContext { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext(), }, MetadataProvider = metadataProvider, ValidatorProvider = Mock.Of <IModelValidatorProvider>(), }; var bindingContext = new DefaultModelBindingContext { ModelMetadata = metadataProvider.GetMetadataForType(modelType), ModelName = "someName", ValueProvider = Mock.Of <IValueProvider>(), ModelState = new ModelStateDictionary(), OperationBindingContext = operationBindingContext, }; return(bindingContext); }
public async Task ModelBinder_ReturnsNothing_IfBinderMatchesButDoesNotSetModel() { // Arrange var bindingContext = new DefaultModelBindingContext { FallbackToEmptyPrefix = true, ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(typeof(List <int>)), ModelName = "someName", ModelState = new ModelStateDictionary(), OperationBindingContext = new OperationBindingContext(), ValueProvider = new SimpleValueProvider { { "someOtherName", "dummyValue" } }, FieldName = "someName", }; var mockIntBinder = new StubModelBinder(context => { context.Result = ModelBindingResult.Failed("someName"); }); var composite = CreateCompositeBinder(mockIntBinder); // Act var result = await composite.BindModelResultAsync(bindingContext); // Assert Assert.Equal(default(ModelBindingResult), result); }
public async Task BindModelAsync_AllComponentsEmpty_DoesNotBind() { // Arrange var modelType = typeof(Date); ModelBindingContext bindingContext = new DefaultModelBindingContext() { ActionContext = CreateActionContextWithServices(), ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(modelType), ModelName = "TheModelName", ModelState = new ModelStateDictionary(), ValueProvider = new SimpleValueProvider() }; var converterMock = new Mock <DateInputModelConverter>(); converterMock.Setup(mock => mock.CanConvertModelType(modelType)).Returns(true); var modelBinder = new DateInputModelBinder(converterMock.Object); // Act await modelBinder.BindModelAsync(bindingContext); // Assert Assert.False(bindingContext.Result.IsModelSet); }
public async Task BindModelAsync_CreatesDataSetForParameter(string methodName, string paramName) { // Arrange var metadata = GetMetadataForParameter(typeof(DataSetModelBinderTest), methodName); var bindingContext = new DefaultModelBindingContext { IsTopLevelObject = true, ModelMetadata = metadata, ModelName = paramName, FieldName = paramName, ValueProvider = new TestValueProvider(new Dictionary <string, object>()), ModelState = new ModelStateDictionary() }; var binder = new DataSetModelBinder <Student>(NullLoggerFactory.Instance); // Act await binder.BindModelAsync(bindingContext); // Assert Assert.True(bindingContext.Result.IsModelSet); Assert.NotNull(bindingContext.Result.Model); Assert.IsAssignableFrom <DataSet <Student> >(bindingContext.Result.Model); var keyValuePair = Assert.Single(bindingContext.ModelState); Assert.Equal(paramName, keyValuePair.Key); Assert.Empty(keyValuePair.Value.Errors); }
private static DefaultModelBindingContext GetBindingContext( IValueProvider valueProvider, IModelBinder innerBinder = null, Type keyValuePairType = null) { var metataProvider = new EmptyModelMetadataProvider(); var bindingContext = new DefaultModelBindingContext { ModelMetadata = metataProvider.GetMetadataForType( keyValuePairType ?? typeof(KeyValuePair <int, string>)), ModelName = "someName", ModelState = new ModelStateDictionary(), ValueProvider = valueProvider, OperationBindingContext = new OperationBindingContext { ModelBinder = innerBinder ?? CreateIntBinder(), MetadataProvider = metataProvider, ValidatorProvider = new DataAnnotationsModelValidatorProvider( new ValidationAttributeAdapterProvider(), new TestOptionsManager <MvcDataAnnotationsLocalizationOptions>(), stringLocalizerFactory: null) } }; return(bindingContext); }
public async Task BindModelAsync_ReturnsNullWhenResponseCannotBeFound() { // Arrange var binder = new OpenIddictModelBinder(); var provider = new EmptyModelMetadataProvider(); var context = new DefaultModelBindingContext { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext(), }, ModelMetadata = provider.GetMetadataForType(typeof(OpenIdConnectResponse)), ValidationState = new ValidationStateDictionary() }; // Act await binder.BindModelAsync(context); // Assert Assert.True(context.Result.IsModelSet); Assert.Null(context.Result.Model); }
public async Task AllComponentsProvider_BindsSuccessfully(Type modelType) { // Arrange ModelBindingContext bindingContext = new DefaultModelBindingContext() { ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(modelType), ModelName = "TheModelName", ModelState = new ModelStateDictionary(), ValueProvider = new SimpleValueProvider() { { "TheModelName.Day", "1" }, { "TheModelName.Month", "4" }, { "TheModelName.Year", "2020" } } }; var modelBinder = new DateInputModelBinder(); // Act await modelBinder.BindModelAsync(bindingContext); // Assert Assert.True(bindingContext.Result.IsModelSet); Assert.IsType <Date>(bindingContext.Result.Model); Date date = (Date)bindingContext.Result.Model; Assert.Equal(2020, date.Year); Assert.Equal(4, date.Month); Assert.Equal(1, date.Day); }
public async Task BindModelAsync_ReturnsNullWhenRequestCannotBeFoundAndExceptionsAreDisabled() { // Arrange var options = Mock.Of <IOptionsMonitor <OpenIddictMvcOptions> >( mock => mock.CurrentValue == new OpenIddictMvcOptions { DisableBindingExceptions = true }); var binder = new OpenIddictMvcBinder(options); var provider = new EmptyModelMetadataProvider(); var context = new DefaultModelBindingContext { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext(), }, ModelMetadata = provider.GetMetadataForType(typeof(OpenIdConnectRequest)) }; // Act await binder.BindModelAsync(context); // Assert Assert.True(context.Result.IsModelSet); Assert.Null(context.Result.Model); Assert.Equal(BindingSource.Special, context.BindingSource); }
public async Task <ModelBindingResult?> BindModelAsync( ParameterDescriptor parameter, ControllerContext controllerContext) { if (parameter == null) { throw new ArgumentNullException(nameof(parameter)); } if (controllerContext == null) { throw new ArgumentNullException(nameof(controllerContext)); } var metadata = _modelMetadataProvider.GetMetadataForType(parameter.ParameterType); var modelBindingContext = DefaultModelBindingContext.CreateBindingContext( controllerContext, new CompositeValueProvider(controllerContext.ValueProviders), metadata, parameter.BindingInfo, parameter.Name); if (parameter.BindingInfo?.BinderModelName != null) { // The name was set explicitly, always use that as the prefix. modelBindingContext.ModelName = parameter.BindingInfo.BinderModelName; } else if (modelBindingContext.ValueProvider.ContainsPrefix(parameter.Name)) { // We have a match for the parameter name, use that as that prefix. modelBindingContext.ModelName = parameter.Name; } else { // No match, fallback to empty string as the prefix. modelBindingContext.ModelName = string.Empty; } var binder = _modelBinderFactory.CreateBinder(new ModelBinderFactoryContext() { BindingInfo = parameter.BindingInfo, Metadata = metadata, CacheToken = parameter, }); await binder.BindModelAsync(modelBindingContext); var modelBindingResult = modelBindingContext.Result; if (modelBindingResult != null && modelBindingResult.Value.IsModelSet) { _validator.Validate( controllerContext, modelBindingContext.ValidationState, modelBindingResult.Value.Key, modelBindingResult.Value.Model); } return(modelBindingResult); }
public async Task BindModelAsyncAddsMatchingFiltersTest() { var context = new DefaultModelBindingContext(); var httpContext = Substitute.For <HttpContext>(); var actionContext = Substitute.For <ActionContext>(); var request = Substitute.For <HttpRequest>(); var values = new Dictionary <string, StringValues> { { "skill", "mySkill" }, { "language", new StringValues(new[] { "english", "spanish" }) }, { "gender", "female" } }; var query = new QueryCollection(values); context.ActionContext = actionContext; actionContext.HttpContext = httpContext; httpContext.Request.Returns(request); request.Query.Returns(query); var sut = new ProfileFilterModelBinder(); await sut.BindModelAsync(context).ConfigureAwait(false); context.Result.IsModelSet.Should().BeTrue(); var actual = context.Result.Model.As <List <ProfileFilter> >(); actual.Should().HaveCount(4); actual.Should().Contain(x => x.CategoryGroup == CategoryGroup.Skill && x.CategoryName == "mySkill"); actual.Should().Contain(x => x.CategoryGroup == CategoryGroup.Language && x.CategoryName == "english"); actual.Should().Contain(x => x.CategoryGroup == CategoryGroup.Language && x.CategoryName == "spanish"); actual.Should().Contain(x => x.CategoryGroup == CategoryGroup.Gender && x.CategoryName == "female"); }
private static DefaultModelBindingContext GetBindingContext(Type modelType) { var metadataProvider = new TestModelMetadataProvider(); metadataProvider.ForType(modelType).BindingDetails(d => d.BindingSource = BindingSource.Services); var modelMetadata = metadataProvider.GetMetadataForType(modelType); var services = new ServiceCollection(); services.AddSingleton <IService>(new Service()); var bindingContext = new DefaultModelBindingContext { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext() { RequestServices = services.BuildServiceProvider(), } }, ModelMetadata = modelMetadata, ModelName = "modelName", FieldName = "modelName", ModelState = new ModelStateDictionary(), BinderModelName = modelMetadata.BinderModelName, BindingSource = modelMetadata.BindingSource, ValidationState = new ValidationStateDictionary(), }; return(bindingContext); }
public async Task BindModelAsync_ReturnsAmbientResponse() { // Arrange var binder = new OpenIddictModelBinder(); var provider = new EmptyModelMetadataProvider(); var response = new OpenIdConnectResponse(); var features = new FeatureCollection(); features.Set(new OpenIdConnectServerFeature { Response = response }); var context = new DefaultModelBindingContext { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext(features), }, ModelMetadata = provider.GetMetadataForType(typeof(OpenIdConnectResponse)), ValidationState = new ValidationStateDictionary() }; // Act await binder.BindModelAsync(context); // Assert Assert.True(context.Result.IsModelSet); Assert.Same(response, context.Result.Model); Assert.True(context.ValidationState[response].SuppressValidation); }
public void BindModel_Null_Source_Returns_Null() { var bindingContext = new DefaultModelBindingContext(); _contentModelBinder.BindModel(bindingContext, null, typeof(ContentType1)); Assert.IsNull(bindingContext.Result.Model); }
public void Null_Model_Binds_To_Null() { var bindingContext = new DefaultModelBindingContext(); _contentModelBinder.BindModel(bindingContext, null, typeof(ContentModel)); Assert.IsNull(bindingContext.Result.Model); }
public void Invalid_Model_Type_Throws_Exception() { var bindingContext = new DefaultModelBindingContext(); Assert.Throws <ModelBindingException>(() => _contentModelBinder.BindModel(bindingContext, "Hello", typeof(IPublishedContent))); }
public async Task BindModelAsync_ThrowsAnExceptionWhenRequestCannotBeFound() { // Arrange var binder = new OpenIddictModelBinder(); var provider = new EmptyModelMetadataProvider(); var context = new DefaultModelBindingContext { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext(), }, ModelMetadata = provider.GetMetadataForType(typeof(OpenIdConnectRequest)) }; // Act and assert var exception = await Assert.ThrowsAsync <InvalidOperationException>(delegate { return(binder.BindModelAsync(context)); }); Assert.Equal("The OpenID Connect request cannot be retrieved from the ASP.NET context. " + "Make sure that 'app.UseAuthentication()' is called before 'app.UseMvc()' " + "and that the action route corresponds to the endpoint path registered via " + "'services.AddOpenIddict().Enable[...]Endpoint(...)'.", exception.Message); }
public async Task BindModelAsyncMatchesCaseInsensitiveCategoryGroupsTest(string key) { var context = new DefaultModelBindingContext(); var httpContext = Substitute.For <HttpContext>(); var actionContext = Substitute.For <ActionContext>(); var request = Substitute.For <HttpRequest>(); var values = new Dictionary <string, StringValues> { { key, "female" } }; var query = new QueryCollection(values); context.ActionContext = actionContext; actionContext.HttpContext = httpContext; httpContext.Request.Returns(request); request.Query.Returns(query); var sut = new ProfileFilterModelBinder(); await sut.BindModelAsync(context).ConfigureAwait(false); context.Result.IsModelSet.Should().BeTrue(); var actual = context.Result.Model.As <List <ProfileFilter> >(); actual.Should().Contain(x => x.CategoryGroup == CategoryGroup.Gender && x.CategoryName == "female"); }
private static DefaultModelBindingContext GetBindingContext(Type modelType) { var metadataProvider = new TestModelMetadataProvider(); metadataProvider.ForType(modelType).BindingDetails(d => d.BindingSource = BindingSource.Services); var modelMetadata = metadataProvider.GetMetadataForType(modelType); var services = new ServiceCollection(); services.AddSingleton<IService>(new Service()); var bindingContext = new DefaultModelBindingContext { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext() { RequestServices = services.BuildServiceProvider(), } }, ModelMetadata = modelMetadata, ModelName = "modelName", FieldName = "modelName", ModelState = new ModelStateDictionary(), BinderModelName = modelMetadata.BinderModelName, BindingSource = modelMetadata.BindingSource, ValidationState = new ValidationStateDictionary(), }; return bindingContext; }
public void EnterNestedScope_FiltersValueProviders_ForValueProviderSource() { // Arrange var metadataProvider = new TestModelMetadataProvider(); metadataProvider .ForProperty(typeof(string), nameof(string.Length)) .BindingDetails(b => b.BindingSource = BindingSource.Query); var original = CreateDefaultValueProvider(); var context = DefaultModelBindingContext.CreateBindingContext( GetActionContext(), original, metadataProvider.GetMetadataForType(typeof(string)), new BindingInfo(), "model"); var propertyMetadata = metadataProvider.GetMetadataForProperty(typeof(string), nameof(string.Length)); // Act context.EnterNestedScope(propertyMetadata, "Length", "Length", model: null); // Assert Assert.Collection( Assert.IsType <CompositeValueProvider>(context.ValueProvider), vp => Assert.Same(original[1], vp)); }
private static DefaultModelBindingContext GetBindingContext( IValueProvider valueProvider, bool isReadOnly = false) { var metadataProvider = new TestModelMetadataProvider(); metadataProvider.ForProperty( typeof(ModelWithIntArrayProperty), nameof(ModelWithIntArrayProperty.ArrayProperty)).BindingDetails(bd => bd.IsReadOnly = isReadOnly); var modelMetadata = metadataProvider.GetMetadataForProperty( typeof(ModelWithIntArrayProperty), nameof(ModelWithIntArrayProperty.ArrayProperty)); var bindingContext = new DefaultModelBindingContext { ModelMetadata = modelMetadata, ModelName = "someName", ModelState = new ModelStateDictionary(), ValueProvider = valueProvider, OperationBindingContext = new OperationBindingContext { MetadataProvider = metadataProvider, }, }; return(bindingContext); }
private static DefaultModelBindingContext GetModelBindingContext( IValueProvider valueProvider, bool isReadOnly = false) { var metadataProvider = new TestModelMetadataProvider(); metadataProvider .ForProperty <ModelWithIListProperty>(nameof(ModelWithIListProperty.ListProperty)) .BindingDetails(bd => bd.IsReadOnly = isReadOnly); var metadata = metadataProvider.GetMetadataForProperty( typeof(ModelWithIListProperty), nameof(ModelWithIListProperty.ListProperty)); var bindingContext = new DefaultModelBindingContext { ModelMetadata = metadata, ModelName = "someName", ModelState = new ModelStateDictionary(), ValueProvider = valueProvider, ValidationState = new ValidationStateDictionary(), FieldName = "testfieldname", }; return(bindingContext); }
/// <summary> /// Reads the JSON HTTP request entity body. /// </summary> /// <param name="context">The <see cref="ResourceExecutingContext"/>.</param> /// <returns> /// A <see cref="Task"/> that on completion provides a <see cref="JObject"/> containing the HTTP request entity /// body. /// </returns> protected virtual async Task <JObject> ReadAsJsonAsync(ResourceExecutingContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var request = context.HttpContext.Request; if (request.Body == null || !request.ContentLength.HasValue || request.ContentLength.Value == 0L || !HttpMethods.IsPost(request.Method)) { // Other filters will log and return errors about these conditions. return(null); } var modelState = context.ModelState; var actionContext = new ActionContext( context.HttpContext, context.RouteData, context.ActionDescriptor, modelState); var valueProviderFactories = context.ValueProviderFactories; var valueProvider = await CompositeValueProvider.CreateAsync(actionContext, valueProviderFactories); var bindingContext = DefaultModelBindingContext.CreateBindingContext( actionContext, valueProvider, _jObjectMetadata, bindingInfo: null, modelName: WebHookConstants.ModelStateBodyModelName); // Read request body. try { await _bodyModelBinder.BindModelAsync(bindingContext); } finally { request.Body.Seek(0L, SeekOrigin.Begin); } if (!bindingContext.ModelState.IsValid) { return(null); } if (!bindingContext.Result.IsModelSet) { throw new InvalidOperationException(Resources.VerifyNotification_ModelBindingFailed); } // Success return((JObject)bindingContext.Result.Model); }
public void Throws_When_Source_Not_Of_Expected_Type() { // Arrange var bindingContext = new DefaultModelBindingContext(); // Act/Assert Assert.Throws <ModelBindingException>(() => _contentModelBinder.BindModel(bindingContext, new NonContentModel(), typeof(ContentModel))); }
private static DefaultModelBindingContext GetBindingContext(Type modelType, HttpContext httpContext) { var metadataProvider = new EmptyModelMetadataProvider(); var bindingContext = new DefaultModelBindingContext { ActionContext = new ActionContext() { HttpContext = httpContext, }, ModelMetadata = metadataProvider.GetMetadataForType(modelType), ModelName = "file", ValidationState = new ValidationStateDictionary(), }; return bindingContext; }
private static DefaultModelBindingContext GetBindingContext(Type modelType) { var metadataProvider = new EmptyModelMetadataProvider(); DefaultModelBindingContext bindingContext = new DefaultModelBindingContext { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext(), }, ModelMetadata = metadataProvider.GetMetadataForType(modelType), ModelName = "someName", ValueProvider = new SimpleValueProvider(), ValidationState = new ValidationStateDictionary(), }; return bindingContext; }
private static DefaultModelBindingContext CreateContext() { var modelBindingContext = new DefaultModelBindingContext() { OperationBindingContext = new OperationBindingContext() { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext(), }, MetadataProvider = new TestModelMetadataProvider(), } }; return modelBindingContext; }
private static DefaultModelBindingContext GetBindingContext( IValueProvider valueProvider, bool isReadOnly = false) { var metadataProvider = new TestModelMetadataProvider(); metadataProvider.ForProperty( typeof(ModelWithIntArrayProperty), nameof(ModelWithIntArrayProperty.ArrayProperty)).BindingDetails(bd => bd.IsReadOnly = isReadOnly); var modelMetadata = metadataProvider.GetMetadataForProperty( typeof(ModelWithIntArrayProperty), nameof(ModelWithIntArrayProperty.ArrayProperty)); var bindingContext = new DefaultModelBindingContext { ModelMetadata = modelMetadata, ModelName = "someName", ModelState = new ModelStateDictionary(), ValueProvider = valueProvider, OperationBindingContext = new OperationBindingContext { MetadataProvider = metadataProvider, }, }; return bindingContext; }
private static DefaultModelBindingContext GetBindingContext(IValueProvider valueProvider) { var bindingContext = new DefaultModelBindingContext() { ModelName = "someName", ModelState = new ModelStateDictionary(), ValueProvider = valueProvider, }; return bindingContext; }
private static DefaultModelBindingContext CreateContext() { var modelBindingContext = new DefaultModelBindingContext() { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext(), }, }; return modelBindingContext; }
private static DefaultModelBindingContext GetBindingContext( Type modelType, HttpContext httpContext = null, IModelMetadataProvider metadataProvider = null) { if (httpContext == null) { httpContext = new DefaultHttpContext(); } if (metadataProvider == null) { metadataProvider = new EmptyModelMetadataProvider(); } var bindingContext = new DefaultModelBindingContext { ActionContext = new ActionContext() { HttpContext = httpContext, }, FieldName = "someField", IsTopLevelObject = true, ModelMetadata = metadataProvider.GetMetadataForType(modelType), ModelName = "someName", ValueProvider = Mock.Of<IValueProvider>(), ModelState = new ModelStateDictionary(), BindingSource = BindingSource.Body, }; return bindingContext; }
public async Task BindModelAsync_CreatesModel_IfIsTopLevelObject() { // Arrange var mockValueProvider = new Mock<IValueProvider>(); mockValueProvider .Setup(o => o.ContainsPrefix(It.IsAny<string>())) .Returns(false); // Mock binder fails to bind all properties. var mockBinder = new StubModelBinder(); var bindingContext = new DefaultModelBindingContext { IsTopLevelObject = true, ModelMetadata = GetMetadataForType(typeof(Person)), ModelName = string.Empty, ValueProvider = mockValueProvider.Object, ModelState = new ModelStateDictionary(), }; var model = new Person(); var testableBinder = new Mock<TestableComplexTypeModelBinder> { CallBase = true }; testableBinder .Setup(o => o.CreateModelPublic(bindingContext)) .Returns(model) .Verifiable(); testableBinder .Setup(o => o.CanBindPropertyPublic(bindingContext, It.IsAny<ModelMetadata>())) .Returns(false); // Act await testableBinder.Object.BindModelAsync(bindingContext); // Assert Assert.True(bindingContext.Result.IsModelSet); var returnedPerson = Assert.IsType<Person>(bindingContext.Result.Model); Assert.Same(model, returnedPerson); testableBinder.Verify(); }
private static DefaultModelBindingContext GetBindingContext( IValueProvider valueProvider, Type keyValuePairType) { var metadataProvider = new TestModelMetadataProvider(); var bindingContext = new DefaultModelBindingContext { ModelMetadata = metadataProvider.GetMetadataForType(keyValuePairType), ModelName = "someName", ModelState = new ModelStateDictionary(), ValueProvider = valueProvider, }; return bindingContext; }
public void CanBindProperty_GetSetProperty(string property) { // Arrange var metadata = GetMetadataForProperty(typeof(PersonWithBindExclusion), property); var bindingContext = new DefaultModelBindingContext() { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext() { RequestServices = new ServiceCollection().BuildServiceProvider(), }, }, ModelMetadata = GetMetadataForType(typeof(PersonWithBindExclusion)), }; var binder = CreateBinder(bindingContext.ModelMetadata); // Act var result = binder.CanBindPropertyPublic(bindingContext, metadata); // Assert Assert.True(result); }
public void CanBindProperty_GetSetProperty_WithBindNever(string property) { // Arrange var metadata = GetMetadataForProperty(typeof(PersonWithBindExclusion), property); var bindingContext = new DefaultModelBindingContext() { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext(), }, ModelMetadata = GetMetadataForType(typeof(PersonWithBindExclusion)), }; var binder = CreateBinder(bindingContext.ModelMetadata); // Act var result = binder.CanBindPropertyPublic(bindingContext, metadata); // Assert Assert.False(result); }
public void CanBindProperty_WithBindInclude(string property, bool expected) { // Arrange var metadata = GetMetadataForProperty(typeof(TypeWithIncludedPropertiesUsingBindAttribute), property); var bindingContext = new DefaultModelBindingContext() { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext() }, ModelMetadata = GetMetadataForType(typeof(TypeWithIncludedPropertiesUsingBindAttribute)), }; var binder = CreateBinder(bindingContext.ModelMetadata); // Act var result = binder.CanBindPropertyPublic(bindingContext, metadata); // Assert Assert.Equal(expected, result); }
public void CanBindProperty_BindingAttributes_OverridingBehavior(string property, bool expected) { // Arrange var metadata = GetMetadataForProperty(typeof(ModelWithMixedBindingBehaviors), property); var bindingContext = new DefaultModelBindingContext() { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext(), }, ModelMetadata = GetMetadataForType(typeof(ModelWithMixedBindingBehaviors)), }; var binder = CreateBinder(bindingContext.ModelMetadata); // Act var result = binder.CanBindPropertyPublic(bindingContext, metadata); // Assert Assert.Equal(expected, result); }
private static DefaultModelBindingContext GetBindingContext( Type modelType, IEnumerable<IInputFormatter> inputFormatters = null, HttpContext httpContext = null, IModelMetadataProvider metadataProvider = null) { if (httpContext == null) { httpContext = new DefaultHttpContext(); } if (inputFormatters == null) { inputFormatters = Enumerable.Empty<IInputFormatter>(); } if (metadataProvider == null) { metadataProvider = new EmptyModelMetadataProvider(); } var operationBindingContext = new OperationBindingContext { ActionContext = new ActionContext() { HttpContext = httpContext, }, InputFormatters = inputFormatters.ToList(), MetadataProvider = metadataProvider, }; var bindingContext = new DefaultModelBindingContext { FieldName = "someField", IsTopLevelObject = true, ModelMetadata = metadataProvider.GetMetadataForType(modelType), ModelName = "someName", ValueProvider = Mock.Of<IValueProvider>(), ModelState = new ModelStateDictionary(), OperationBindingContext = operationBindingContext, BindingSource = BindingSource.Body, }; return bindingContext; }
private static DefaultModelBindingContext GetModelBindingContext( IValueProvider valueProvider, bool isReadOnly = false) { var metadataProvider = new TestModelMetadataProvider(); metadataProvider .ForProperty<ModelWithIListProperty>(nameof(ModelWithIListProperty.ListProperty)) .BindingDetails(bd => bd.IsReadOnly = isReadOnly); var metadata = metadataProvider.GetMetadataForProperty( typeof(ModelWithIListProperty), nameof(ModelWithIListProperty.ListProperty)); var bindingContext = new DefaultModelBindingContext { ModelMetadata = metadata, ModelName = "someName", ModelState = new ModelStateDictionary(), ValueProvider = valueProvider, ValidationState = new ValidationStateDictionary(), FieldName = "testfieldname", }; return bindingContext; }
public void CreateModel_InstantiatesInstanceOfMetadataType() { // Arrange var bindingContext = new DefaultModelBindingContext { ModelMetadata = GetMetadataForType(typeof(Person)) }; var binder = CreateBinder(bindingContext.ModelMetadata); // Act var model = binder.CreateModelPublic(bindingContext); // Assert Assert.IsType<Person>(model); }
private static DefaultModelBindingContext CreateContext() { var modelBindingContext = new DefaultModelBindingContext() { ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext(), }, ModelState = new ModelStateDictionary(), ValidationState = new ValidationStateDictionary(), }; return modelBindingContext; }
private static DefaultModelBindingContext GetModelBindingContext( bool isReadOnly, IDictionary<string, string> values = null) { var metadataProvider = new TestModelMetadataProvider(); metadataProvider .ForProperty<ModelWithIDictionaryProperty>(nameof(ModelWithIDictionaryProperty.DictionaryProperty)) .BindingDetails(bd => bd.IsReadOnly = isReadOnly); var metadata = metadataProvider.GetMetadataForProperty( typeof(ModelWithIDictionaryProperty), nameof(ModelWithIDictionaryProperty.DictionaryProperty)); var valueProvider = new SimpleValueProvider(); foreach (var kvp in values) { valueProvider.Add(kvp.Key, string.Empty); } var bindingContext = new DefaultModelBindingContext { ModelMetadata = metadata, ModelName = "someName", ModelState = new ModelStateDictionary(), ValueProvider = valueProvider, ValidationState = new ValidationStateDictionary(), }; return bindingContext; }