private IServiceProvider CreateServices() { var services = new Mock<IServiceProvider>(MockBehavior.Strict); var options = new MvcOptions(); options.OutputFormatters.Add(new JsonOutputFormatter()); var optionsAccessor = new Mock<IOptions<MvcOptions>>(); optionsAccessor.SetupGet(o => o.Options) .Returns(options); var mockActionBindingContext = new Mock<IScopedInstance<ActionBindingContext>>(); var bindingContext = new ActionBindingContext { OutputFormatters = options.OutputFormatters }; mockActionBindingContext .SetupGet(o => o.Value) .Returns(bindingContext); services.Setup(o => o.GetService(typeof(IScopedInstance<ActionBindingContext>))) .Returns(mockActionBindingContext.Object); services.Setup(s => s.GetService(typeof(IOptions<MvcOptions>))) .Returns(optionsAccessor.Object); services.Setup(s => s.GetService(typeof(ILogger<ObjectResult>))) .Returns(new Mock<ILogger<ObjectResult>>().Object); return services.Object; }
public async Task<IDictionary<string, object>> BindActionArgumentsAsync( ActionContext actionContext, ActionBindingContext actionBindingContext, object controller) { var actionDescriptor = actionContext.ActionDescriptor as ControllerActionDescriptor; if (actionDescriptor == null) { throw new ArgumentException( Resources.FormatActionDescriptorMustBeBasedOnControllerAction( typeof(ControllerActionDescriptor)), nameof(actionContext)); } var operationBindingContext = GetOperationBindingContext(actionContext, actionBindingContext); var controllerProperties = new Dictionary<string, object>(StringComparer.Ordinal); await PopulateArgumentsAsync( operationBindingContext, actionContext.ModelState, controllerProperties, actionDescriptor.BoundProperties); var controllerType = actionDescriptor.ControllerTypeInfo.AsType(); ActivateProperties(controller, controllerType, controllerProperties); var actionArguments = new Dictionary<string, object>(StringComparer.Ordinal); await PopulateArgumentsAsync( operationBindingContext, actionContext.ModelState, actionArguments, actionDescriptor.Parameters); return actionArguments; }
public Task<ActionBindingContext> GetActionBindingContextAsync(ActionContext actionContext) { if (_bindingContext != null) { if (actionContext == _bindingContext.Item1) { return Task.FromResult(_bindingContext.Item2); } } var factoryContext = new ValueProviderFactoryContext( actionContext.HttpContext, actionContext.RouteData.Values); var valueProvider = _compositeValueProviderFactory.GetValueProvider(factoryContext); var context = new ActionBindingContext( actionContext, _modelMetadataProvider, _compositeModelBinder, valueProvider, _inputFormatterProvider, _validatorProviders); _bindingContext = new Tuple<ActionContext, ActionBindingContext>(actionContext, context); return Task.FromResult(context); }
private IServiceProvider CreateServices() { var services = new ServiceCollection(); services.Add(new ServiceDescriptor( typeof(ILogger<ObjectResult>), new Logger<ObjectResult>(NullLoggerFactory.Instance))); var optionsAccessor = new MockMvcOptionsAccessor(); optionsAccessor.Options.OutputFormatters.Add(new JsonOutputFormatter()); services.Add(new ServiceDescriptor(typeof(IOptions<MvcOptions>), optionsAccessor)); var bindingContext = new ActionBindingContext { OutputFormatters = optionsAccessor.Options.OutputFormatters, }; var bindingContextAccessor = new ActionBindingContextAccessor { ActionBindingContext = bindingContext, }; services.Add(new ServiceDescriptor(typeof(IActionBindingContextAccessor), bindingContextAccessor)); return services.BuildServiceProvider(); }
private static ActionContext CreateMockActionContext( IEnumerable<IOutputFormatter> outputFormatters, HttpResponse response = null, string requestAcceptHeader = "application/*", string requestContentType = "application/json", string requestAcceptCharsetHeader = "", bool respectBrowserAcceptHeader = false, bool setupActionBindingContext = true) { var httpContext = new Mock<HttpContext>(); if (response != null) { httpContext.Setup(o => o.Response).Returns(response); } var content = "{name: 'Person Name', Age: 'not-an-age'}"; var contentBytes = Encoding.UTF8.GetBytes(content); var request = new DefaultHttpContext().Request; request.Headers["Accept-Charset"] = requestAcceptCharsetHeader; request.Headers["Accept"] = requestAcceptHeader; request.ContentType = requestContentType; request.Body = new MemoryStream(contentBytes); httpContext.Setup(o => o.Features).Returns(new FeatureCollection()); httpContext.Setup(o => o.Request).Returns(request); httpContext.Setup(o => o.RequestServices).Returns(GetServiceProvider()); var optionsAccessor = new TestOptionsManager<MvcOptions>(); foreach (var formatter in outputFormatters) { optionsAccessor.Value.OutputFormatters.Add(formatter); } optionsAccessor.Value.RespectBrowserAcceptHeader = respectBrowserAcceptHeader; httpContext.Setup(o => o.RequestServices.GetService(typeof(IOptions<MvcOptions>))) .Returns(optionsAccessor); httpContext.Setup(o => o.RequestServices.GetService(typeof(ILogger<ObjectResult>))) .Returns(new Mock<ILogger<ObjectResult>>().Object); ActionBindingContext actionBindingContext = null; if (setupActionBindingContext) { actionBindingContext = new ActionBindingContext { OutputFormatters = outputFormatters.ToList() }; } httpContext.Setup(o => o.RequestServices.GetService(typeof(IActionBindingContextAccessor))) .Returns(new ActionBindingContextAccessor() { ActionBindingContext = actionBindingContext }); return new ActionContext(httpContext.Object, new RouteData(), new ActionDescriptor()); }
private OperationBindingContext GetOperationBindingContext( ActionContext actionContext, ActionBindingContext bindingContext) { return new OperationBindingContext { ModelBinder = bindingContext.ModelBinder, ValidatorProvider = bindingContext.ValidatorProvider, MetadataProvider = _modelMetadataProvider, HttpContext = actionContext.HttpContext, ValueProvider = bindingContext.ValueProvider, }; }
private static HttpContext GetHttpContext() { var httpContext = new DefaultHttpContext(); httpContext.Request.PathBase = new PathString(""); httpContext.Response.Body = new MemoryStream(); var services = new Mock<IServiceProvider>(); httpContext.RequestServices = services.Object; var optionsAccessor = new MockMvcOptionsAccessor(); optionsAccessor.Options.OutputFormatters.Add(new StringOutputFormatter()); optionsAccessor.Options.OutputFormatters.Add(new JsonOutputFormatter()); services.Setup(p => p.GetService(typeof(IOptions<MvcOptions>))) .Returns(optionsAccessor); services.Setup(s => s.GetService(typeof(ILogger<ObjectResult>))) .Returns(new Mock<ILogger<ObjectResult>>().Object); var actionBindingContext = new ActionBindingContext { OutputFormatters = optionsAccessor.Options.OutputFormatters }; services.Setup(o => o.GetService(typeof(IActionBindingContextAccessor))) .Returns(new ActionBindingContextAccessor() { ActionBindingContext = actionBindingContext }); return httpContext; }
private static BodyModelBinder GetBodyBinder(HttpContext httpContext, IInputFormatter inputFormatter) { var actionContext = CreateActionContext(httpContext); var inputFormatterSelector = new Mock<IInputFormatterSelector>(); inputFormatterSelector .Setup(o => o.SelectFormatter( It.IsAny<IReadOnlyList<IInputFormatter>>(), It.IsAny<InputFormatterContext>())) .Returns(inputFormatter); var bodyValidationPredicatesProvider = new Mock<IValidationExcludeFiltersProvider>(); bodyValidationPredicatesProvider.SetupGet(o => o.ExcludeFilters) .Returns(new List<IExcludeTypeValidationFilter>()); var bindingContext = new ActionBindingContext() { InputFormatters = new List<IInputFormatter>(), }; var bindingContextAccessor = new MockScopedInstance<ActionBindingContext>() { Value = bindingContext, }; var binder = new BodyModelBinder( actionContext, bindingContextAccessor, inputFormatterSelector.Object, bodyValidationPredicatesProvider.Object); return binder; }
private static HttpContext GetHttpContext() { var httpContext = new Mock<HttpContext>(); var realContext = new DefaultHttpContext(); var request = realContext.Request; request.PathBase = new PathString(""); var response = realContext.Response; response.Body = new MemoryStream(); httpContext.Setup(o => o.Request) .Returns(request); httpContext.Setup(o => o.Response) .Returns(response); var optionsAccessor = new TestOptionsManager<MvcOptions>(); optionsAccessor.Value.OutputFormatters.Add(new StringOutputFormatter()); optionsAccessor.Value.OutputFormatters.Add(new JsonOutputFormatter()); httpContext .Setup(p => p.RequestServices.GetService(typeof(IOptions<MvcOptions>))) .Returns(optionsAccessor); httpContext .Setup(p => p.RequestServices.GetService(typeof(ILogger<ObjectResult>))) .Returns(new Mock<ILogger<ObjectResult>>().Object); var actionBindingContext = new ActionBindingContext() { OutputFormatters = optionsAccessor.Value.OutputFormatters }; httpContext .Setup(o => o.RequestServices.GetService(typeof(IActionBindingContextAccessor))) .Returns(new ActionBindingContextAccessor() { ActionBindingContext = actionBindingContext }); return httpContext.Object; }
public async Task Invoke_UsesDefaultValuesIfNotBound() { // Arrange var actionDescriptor = new ReflectedActionDescriptor { MethodInfo = typeof(TestController).GetTypeInfo() .DeclaredMethods .First(m => m.Name.Equals("ActionMethodWithDefaultValues", StringComparison.Ordinal)), Parameters = new List<ParameterDescriptor> { new ParameterDescriptor { Name = "value", ParameterBindingInfo = new ParameterBindingInfo("value", typeof(int)) } }, FilterDescriptors = new List<FilterDescriptor>() }; var binder = new Mock<IModelBinder>(); var metadataProvider = new EmptyModelMetadataProvider(); binder.Setup(b => b.BindModelAsync(It.IsAny<ModelBindingContext>())) .Returns(Task.FromResult(result: false)); var context = new Mock<HttpContext>(); context.SetupGet(c => c.Items) .Returns(new Dictionary<object, object>()); var routeContext = new RouteContext(context.Object); var actionContext = new ActionContext(routeContext, actionDescriptor); var bindingContext = new ActionBindingContext(actionContext, Mock.Of<IModelMetadataProvider>(), binder.Object, Mock.Of<IValueProvider>(), Mock.Of<IInputFormatterProvider>(), Enumerable.Empty<IModelValidatorProvider>()); var actionBindingContextProvider = new Mock<IActionBindingContextProvider>(); actionBindingContextProvider.Setup(p => p.GetActionBindingContextAsync(It.IsAny<ActionContext>())) .Returns(Task.FromResult(bindingContext)); var controllerFactory = new Mock<IControllerFactory>(); controllerFactory.Setup(c => c.CreateController(It.IsAny<ActionContext>())) .Returns(new TestController()); var invoker = new ReflectedActionInvoker(actionContext, actionDescriptor, controllerFactory.Object, actionBindingContextProvider.Object, Mock.Of<INestedProviderManager<FilterProviderContext>>()); // Act await invoker.InvokeActionAsync(); // Assert Assert.Equal(5, context.Object.Items["Result"]); }
public async Task GetActionArguments_AddsActionArgumentsToModelStateDictionary_IfBinderReturnsTrue() { // Arrange Func<object, int> method = x => 1; var actionDescriptor = new ReflectedActionDescriptor { MethodInfo = method.Method, Parameters = new List<ParameterDescriptor> { new ParameterDescriptor { Name = "foo", ParameterBindingInfo = new ParameterBindingInfo("foo", typeof(object)) } } }; var value = "Hello world"; var binder = new Mock<IModelBinder>(); var metadataProvider = new EmptyModelMetadataProvider(); binder.Setup(b => b.BindModelAsync(It.IsAny<ModelBindingContext>())) .Callback((ModelBindingContext context) => { context.ModelMetadata = metadataProvider.GetMetadataForType(modelAccessor: null, modelType: typeof(string)); context.Model = value; }) .Returns(Task.FromResult(result: true)); var actionContext = new ActionContext(new RouteContext(Mock.Of<HttpContext>()), actionDescriptor); var bindingContext = new ActionBindingContext(actionContext, Mock.Of<IModelMetadataProvider>(), binder.Object, Mock.Of<IValueProvider>(), Mock.Of<IInputFormatterProvider>(), Enumerable.Empty<IModelValidatorProvider>()); var actionBindingContextProvider = new Mock<IActionBindingContextProvider>(); actionBindingContextProvider.Setup(p => p.GetActionBindingContextAsync(It.IsAny<ActionContext>())) .Returns(Task.FromResult(bindingContext)); var invoker = new ReflectedActionInvoker(actionContext, actionDescriptor, Mock.Of<IControllerFactory>(), actionBindingContextProvider.Object, Mock.Of<INestedProviderManager<FilterProviderContext>>()); var modelStateDictionary = new ModelStateDictionary(); // Act var result = await invoker.GetActionArguments(modelStateDictionary); // Assert Assert.Equal(1, result.Count); Assert.Equal(value, result["foo"]); }
public async Task GetActionArguments_DoesNotAddActionArgumentsToModelStateDictionary_IfBinderReturnsFalse() { // Arrange Func<object, int> method = x => 1; var actionDescriptor = new ReflectedActionDescriptor { MethodInfo = method.Method, Parameters = new List<ParameterDescriptor> { new ParameterDescriptor { Name = "foo", ParameterBindingInfo = new ParameterBindingInfo("foo", typeof(object)) } } }; var binder = new Mock<IModelBinder>(); binder.Setup(b => b.BindModelAsync(It.IsAny<ModelBindingContext>())) .Returns(Task.FromResult(result: false)); var actionContext = new ActionContext(new RouteContext(Mock.Of<HttpContext>()), actionDescriptor); var bindingContext = new ActionBindingContext(actionContext, Mock.Of<IModelMetadataProvider>(), binder.Object, Mock.Of<IValueProvider>(), Mock.Of<IInputFormatterProvider>(), Enumerable.Empty<IModelValidatorProvider>()); var actionBindingContextProvider = new Mock<IActionBindingContextProvider>(); actionBindingContextProvider.Setup(p => p.GetActionBindingContextAsync(It.IsAny<ActionContext>())) .Returns(Task.FromResult(bindingContext)); var invoker = new ReflectedActionInvoker(actionContext, actionDescriptor, Mock.Of<IControllerFactory>(), actionBindingContextProvider.Object, Mock.Of<INestedProviderManager<FilterProviderContext>>()); var modelStateDictionary = new ModelStateDictionary(); // Act var result = await invoker.GetActionArguments(modelStateDictionary); // Assert Assert.Empty(result); }
internal static ModelBindingContext GetModelBindingContext(ModelMetadata modelMetadata, ActionBindingContext actionBindingContext) { Predicate <string> propertyFilter = propertyName => BindAttribute.IsPropertyAllowed(propertyName, modelMetadata.IncludedProperties, modelMetadata.ExcludedProperties); var modelBindingContext = new ModelBindingContext { ModelName = modelMetadata.ModelName ?? modelMetadata.PropertyName, ModelMetadata = modelMetadata, ModelState = actionBindingContext.ActionContext.ModelState, ModelBinder = actionBindingContext.ModelBinder, ValidatorProvider = actionBindingContext.ValidatorProvider, MetadataProvider = actionBindingContext.MetadataProvider, HttpContext = actionBindingContext.ActionContext.HttpContext, PropertyFilter = propertyFilter, // Fallback only if there is no explicit model name set. FallbackToEmptyPrefix = modelMetadata.ModelName == null, ValueProvider = actionBindingContext.ValueProvider, }; return(modelBindingContext); }