Пример #1
0
        public void ModelBinderGetParameterValues_UnknownSourceActionParameter_ThrowsException()
        {
            var  collection = new ModelBinderCollection(new JsonSerializer(), Fakes.FakeServiceProvider.GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever());
            bool error      = false;

            try
            {
                var action = new ActionContext();
                action.RouteSegments = new[] { new RouteSegment("action1") };
                action.Parameters    = new[]
                {
                    new ActionParameter(action, collection)
                    {
                        Type            = typeof(ModelBinderCollectionTests),
                        ParameterSource = ParameterSources.Unknown,
                        Name            = "param1"
                    }
                };
                action.ParentController = new ControllerContext
                {
                    RouteAndName = "ctrl1"
                };
                collection.GetParameterValues(Fakes.FakeHttpRequest.WithGetMethod(), action);
            }
            catch (ArgumentException ex)
            {
                error = ex.Message.Contains("has unknown source");
            }
            Assert.True(error);
        }
        public void ModelBinderCollectionDoesSupportType_TypeFromBody_IsSupported()
        {
            var  collection = new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object);
            bool supports   = collection.DoesSupportType(typeof(ModelBinderCollectionTests), Contracts.Models.ParameterSources.Body);

            Assert.True(supports);
        }
Пример #3
0
        public void ModelBinderCollectionDoesSupportType_TypeFromBody_IsSupported()
        {
            var  collection = new ModelBinderCollection(new JsonSerializer(), Fakes.FakeServiceProvider.GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever());
            bool supports   = collection.DoesSupportType(typeof(ModelBinderCollectionTests), Contracts.Models.ParameterSources.Body);

            Assert.True(supports);
        }
    private static ModelBinderCollection GetModelBinderCollection(BindingContext bindingContext)
    {
        if (bindingContext.GetService(typeof(ModelBinderCollection)) is not ModelBinderCollection modelBinders)
        {
            modelBinders = new ModelBinderCollection();
            bindingContext.AddService(typeof(ModelBinderCollection), _ => modelBinders);
        }

        return(modelBinders);
    }
        internal ModelConfigurationSettings()
        {
            _binders = new ModelBinderCollection();
			_valueProviders = new ValueProviderFactoryCollection();
			_validatorProviders = new ModelValidatorProviderCollection();

			InitDefaultBinders();
			InitDefaultBinderProviders();
			InitDefaultValueProviders();
			InitDefaultValidatorProviders();
        }
Пример #6
0
        internal ModelConfigurationSettings()
        {
            _binders            = new ModelBinderCollection();
            _valueProviders     = new ValueProviderFactoryCollection();
            _validatorProviders = new ModelValidatorProviderCollection();

            InitDefaultBinders();
            InitDefaultBinderProviders();
            InitDefaultValueProviders();
            InitDefaultValidatorProviders();
        }
Пример #7
0
        public void ModelBinderCollection_AddingNewModelBinder_AddsSupportForNewType()
        {
            var mock = new Mock <IQueryModelBinder>();

            mock.SetupGet(x => x.SupportedTypes).Returns(new [] { typeof(ModelBinderCollectionTests) });

            var collection = new ModelBinderCollection(new JsonSerializer(), Fakes.FakeServiceProvider.GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever());

            collection.AddAdditionalQueryModelBinder(mock.Object);
            var containsCustomType = collection.GetSupportedTypesFromUrl().Contains(typeof(ModelBinderCollectionTests));

            Assert.True(containsCustomType);
        }
Пример #8
0
        private void Initialize(IServiceProvider services)
        {
            _logger.LogInformation("LiteApi middleware initialization started");
            Options.InternalServiceResolver.RegisterInstance <IAuthorizationPolicyStore>(Options.AuthorizationPolicyStore);

            IControllerDiscoverer ctrlDiscoverer = Options.InternalServiceResolver.GetControllerDiscoverer();

            List <ControllerContext> ctrlContexts = new List <ControllerContext>();

            foreach (var assembly in Options.ControllerAssemblies)
            {
                ctrlContexts.AddRange(ctrlDiscoverer.GetControllers(assembly));
            }

            var actions = ctrlContexts.SelectMany(x => x.Actions).ToArray();

            IControllerBuilder    ctrlBuilder = Options.InternalServiceResolver.GetControllerBuilder();
            ModelBinderCollection modelBinder = new ModelBinderCollection(Options.InternalServiceResolver.GetJsonSerializer(), services);

            foreach (IQueryModelBinder qmb in Options.AdditionalQueryModelBinders)
            {
                modelBinder.AddAdditionalQueryModelBinder(qmb);
            }

            var authPolicyStore             = Options.AuthorizationPolicyStore;
            IControllersValidator validator = Options.InternalServiceResolver.GetControllerValidator();
            var errors = validator.GetValidationErrors(ctrlContexts.ToArray()).ToArray();

            if (errors.Any())
            {
                _logger.LogError("One or more errors occurred while initializing LiteApi middleware. Check next log entry/entries.");
                foreach (var error in errors)
                {
                    _logger.LogError(error);
                }
                string allErrors = "\n\n --------- \n\n" + string.Join("\n\n --------- \n\n", errors);
                throw new LiteApiRegistrationException($"Failed to initialize {nameof(LiteApiMiddleware)}, see property Errors, log if enabled, or check erros listed below." + allErrors, errors);
            }

            Func <Type, bool> isRegistered = (type) => Options.InternalServiceResolver.IsServiceRegistered(type);

            if (!isRegistered(typeof(IPathResolver)))
            {
                Options.InternalServiceResolver.RegisterInstance <IPathResolver>(new PathResolver(ctrlContexts.ToArray()));
            }

            if (!isRegistered(typeof(IModelBinder)))
            {
                Options.InternalServiceResolver.RegisterInstance <IModelBinder>(modelBinder);
            }
        }
Пример #9
0
        public void ModelBinderCollection_NullSeralizer_ThrowsException()
        {
            bool error = false;

            try
            {
                var m = new ModelBinderCollection(null, Fakes.FakeServiceProvider.GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever());
            }
            catch (ArgumentNullException)
            {
                error = true;
            }
            Assert.True(error);
        }
        public void ModelBinderCollection_NullSeralizer_ThrowsException()
        {
            bool error = false;

            try
            {
                var m = new ModelBinderCollection(null, new Moq.Mock <IServiceProvider>().Object);
            }
            catch (ArgumentNullException)
            {
                error = true;
            }
            Assert.True(error);
        }
        public void ModelBinderCollectionDoesSupportType_FromUnknownSource_ThrowsException()
        {
            var  collection = new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object);
            bool error      = false;

            try
            {
                collection.DoesSupportType(typeof(int), Contracts.Models.ParameterSources.Unknown);
            }
            catch
            {
                error = true;
            }
            Assert.True(error);
        }
Пример #12
0
        public void ModelBinder_IEnumerableOfChars_CanParse()
        {
            IControllerDiscoverer discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.CollectionController));
            var ctrl    = discoverer.GetControllers(null).Single();
            var action  = ctrl.Actions.Single(x => x.Name == "get5");
            var mb      = new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object);
            var request = Fakes.FakeHttpRequest.WithGetMethod()
                          .AddQuery("data", "a", "b", "c", "d", "e");

            object[] parameters = mb.GetParameterValues(request, action);
            Assert.Equal(1, parameters.Length);
            var collectionFromParams = (IEnumerable <char>)parameters[0];

            Assert.Equal(new[] { 'a', 'b', 'c', 'd', 'e' }.AsEnumerable(), collectionFromParams);
        }
Пример #13
0
        public void ModelBinder_ArrayOfStrings_CanParse()
        {
            IControllerDiscoverer discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.CollectionController));
            var ctrl    = discoverer.GetControllers(null).Single();
            var action  = ctrl.Actions.Single(x => x.Name == "get1");
            var mb      = new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object);
            var request = Fakes.FakeHttpRequest.WithGetMethod()
                          .AddQuery("data", "1", "1", "2", "5678", "abcd");

            object[] parameters = mb.GetParameterValues(request, action);
            Assert.Equal(1, parameters.Length);
            var arrayFromParams = (string[])parameters[0];

            Assert.Equal(new[] { "1", "1", "2", "5678", "abcd" }, arrayFromParams);
        }
Пример #14
0
        public void ModelBinderCollectionAddAdditionalQueryModelBinder_NullQueryModelBinder_ThrowsException()
        {
            bool error      = false;
            var  collection = new ModelBinderCollection(new JsonSerializer(), Fakes.FakeServiceProvider.GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever());

            try
            {
                collection.AddAdditionalQueryModelBinder(null);
            }
            catch (ArgumentNullException)
            {
                error = true;
            }
            Assert.True(error);
        }
        public void ModelBinderCollectionAddAdditionalQueryModelBinder_NullQueryModelBinder_ThrowsException()
        {
            bool error      = false;
            var  collection = new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object);

            try
            {
                collection.AddAdditionalQueryModelBinder(null);
            }
            catch (ArgumentNullException)
            {
                error = true;
            }
            Assert.True(error);
        }
Пример #16
0
        public void ModelBinderCollectionDoesSupportType_FromUnknownSource_ThrowsException()
        {
            var  collection = new ModelBinderCollection(new JsonSerializer(), Fakes.FakeServiceProvider.GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever());
            bool error      = false;

            try
            {
                collection.DoesSupportType(typeof(int), Contracts.Models.ParameterSources.Unknown);
            }
            catch
            {
                error = true;
            }
            Assert.True(error);
        }
Пример #17
0
        private void AssertCanParseSimpleParam <T>()
        {
            Type type;
            Type nullableArg;
            bool isNullable = false;

            if (typeof(T).GetTypeInfo().IsNullable(out nullableArg))
            {
                type       = nullableArg;
                isNullable = true;
            }
            else
            {
                type = typeof(T);
            }

            object value = "";

            if (typeof(T) == typeof(TestEnum))
            {
                value = TestEnum.TestValueTest;
            }
            else if (typeof(T) != typeof(string))
            {
                value = Activator.CreateInstance(type);
            }

            string      actionName = "Action_" + type.Name + (isNullable ? "_Nullable" : "");
            string      url        = "/ParameterParsing/" + actionName;
            HttpContext ctx        = new Fakes.FakeHttpContext();

            ctx.SetLiteApiOptions(LiteApiOptions.Default);
            var request = ctx.Request as Fakes.FakeHttpRequest;

            request.Path = url;
            request.AddQuery("p", value.ToString());
            var discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.ParameterParsingController));
            var ctrl       = discoverer.GetControllers(null).Single();
            var action     = ctrl.Actions.Single(x => x.Name == actionName.ToLower());

            ctx.SetActionContext(action);

            ModelBinderCollection mb = new ModelBinderCollection(new JsonSerializer(), Fakes.FakeServiceProvider.GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever());

            object[] parameters = mb.GetParameterValues(request, action);
            Assert.Equal(value, parameters.Single());
        }
Пример #18
0
        public void ModelBinder_ListOfNullableIntegers_CanParse()
        {
            IControllerDiscoverer discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.CollectionController));
            var ctrl    = discoverer.GetControllers(null).Single();
            var action  = ctrl.Actions.Single(x => x.Name == "get3");
            var mb      = new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object);
            var request = Fakes.FakeHttpRequest.WithGetMethod()
                          .AddQuery("data", "1", "", "1", "2", "5678");

            object[] parameters = mb.GetParameterValues(request, action);
            Assert.Equal(1, parameters.Length);
            var listFromParams = (List <int?>)parameters[0];

            Assert.Equal(new List <int?>()
            {
                1, null, 1, 2, 5678
            }, listFromParams);
        }
Пример #19
0
        public async Task CanGetParameterFromService()
        {
            IControllerDiscoverer discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.ServiceProvidedParameterController));
            var ctrl    = discoverer.GetControllers(null).Single();
            var action  = ctrl.Actions.Single();
            var mb      = new ModelBinderCollection(new JsonSerializer(), GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever());
            var httpCtx = new Fakes.FakeHttpContext();

            (httpCtx.Request as Fakes.FakeHttpRequest).AddQuery("i", "1");
            object[] parameters = mb.GetParameterValues(httpCtx.Request, action);
            Assert.Equal(2, parameters.Length);
            Assert.True(typeof(Controllers.IIncrementService).IsAssignableFrom(parameters[1].GetType()));

            ActionInvoker invoker = new ActionInvoker(new ControllerBuilder(GetServiceProvider()), mb, new JsonSerializer());
            await invoker.Invoke(httpCtx, action);

            var result = httpCtx.Response.ReadBody();

            Assert.Equal("2", result);
        }
Пример #20
0
        public void ModelBinder_ListOfNullableGuids_CanParse()
        {
            IControllerDiscoverer discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.CollectionController));
            var ctrl    = discoverer.GetControllers(null).Single();
            var action  = ctrl.Actions.Single(x => x.Name == "get4");
            var mb      = new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object);
            var request = Fakes.FakeHttpRequest.WithGetMethod()
                          .AddQuery("data", "b5477041395b47e8ad52605a42462936", "", "{aa2ec3ca-c3e7-4695-be0c-0c33e527515b}", "d29f0102-2c99-4033-ad65-672f6db25a23");

            object[] parameters = mb.GetParameterValues(request, action);
            Assert.Equal(1, parameters.Length);
            var listFromParams = (List <Guid?>)parameters[0];
            var expected       = new List <Guid?>()
            {
                Guid.Parse("b5477041395b47e8ad52605a42462936"),
                null,
                Guid.Parse("{aa2ec3ca-c3e7-4695-be0c-0c33e527515b}"),
                Guid.Parse("d29f0102-2c99-4033-ad65-672f6db25a23")
            };

            Assert.Equal(expected, listFromParams);
        }
Пример #21
0
        public void ModelBinder_ComplexFromBodyParameter_CanParse()
        {
            IControllerDiscoverer discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.CollectionController));
            var ctrl    = discoverer.GetControllers(null).Single();
            var action  = ctrl.Actions.Single(x => x.Name == "post7");
            var mb      = new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object);
            var request = Fakes.FakeHttpRequest.WithPostMethod()
                          .WriteBody(@"
[
    { ""Item1"": 0, ""Item2"": ""0"" },
    { ""Item1"": 1, ""Item2"": ""2"" },
    { ""Item1"": 3, ""Item2"": ""44"" },
]
");

            object[] parameters = mb.GetParameterValues(request, action);
            Assert.Equal(1, parameters.Length);
            var collectionFromParams = (IEnumerable <Tuple <int, string> >)parameters[0];

            Tuple <int, string>[] expected = { Tuple.Create(0, "0"), Tuple.Create(1, "2"), Tuple.Create(3, "44") };
            Assert.Equal(expected, collectionFromParams);
        }
Пример #22
0
        public void ModelBinder_Dictionary_CanParse()
        {
            IControllerDiscoverer discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.CollectionController));
            var ctrl    = discoverer.GetControllers(null).Single();
            var action  = ctrl.Actions.Single(x => x.Name == "get6");
            var mb      = new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object);
            var request = Fakes.FakeHttpRequest.WithGetMethod()
                          .AddQuery("data.1", "a")
                          .AddQuery("data.2", "b")
                          .AddQuery("data.3", "c")
                          .AddQuery("data.4", "d");

            object[] parameters = mb.GetParameterValues(request, action);
            Assert.Equal(1, parameters.Length);
            var collectionFromParams = (IDictionary <int, string>)parameters[0];
            var expected             = new Dictionary <int, string>
            {
                { 1, "a" }, { 2, "b" }, { 3, "c" }, { 4, "d" }
            } as IDictionary <int, string>;

            Assert.Equal(expected, collectionFromParams);
        }
Пример #23
0
        private void AssertCanParseSimpleParam <T>()
        {
            Type type;
            Type nullableArg;
            bool isNullable = false;

            if (typeof(T).GetTypeInfo().IsNullable(out nullableArg))
            {
                type       = nullableArg;
                isNullable = true;
            }
            else
            {
                type = typeof(T);
            }

            object value = "";

            if (typeof(T) != typeof(string))
            {
                value = Activator.CreateInstance(type);
            }

            string actionName = "Action_" + type.Name + (isNullable ? "_Nullable" : "");
            string url        = "/ParameterParsing/" + actionName;
            var    request    = Fakes.FakeHttpRequest.WithGetMethod();

            request.Path = url;
            request.AddQuery("p", value.ToString());
            var discoverer = new Fakes.FakeLimitedControllerDiscoverer(typeof(Controllers.ParameterParsingController));
            var ctrl       = discoverer.GetControllers(null).Single();
            var action     = ctrl.Actions.Single(x => x.Name == actionName.ToLower());

            ModelBinderCollection mb = new ModelBinderCollection(new JsonSerializer(), new Moq.Mock <IServiceProvider>().Object);

            object[] parameters = mb.GetParameterValues(request, action);
            Assert.Equal(value, parameters.Single());
        }
Пример #24
0
        public void ModelBinderGetParameterValues_UnsuportedActionParameterFromQuery_ThrowsException()
        {
            var  collection = new ModelBinderCollection(new JsonSerializer(), Fakes.FakeServiceProvider.GetServiceProvider(), new Fakes.FakeDefaultLiteApiOptionsRetriever());
            bool error      = false;

            try
            {
                var action = new ActionContext();
                action.Parameters = new[]
                {
                    new ActionParameter(action, collection)
                    {
                        Type            = typeof(ModelBinderCollectionTests),
                        ParameterSource = ParameterSources.Query
                    }
                };
                collection.GetParameterValues(Fakes.FakeHttpRequest.WithGetMethod(), action);
            }
            catch (Exception ex)
            {
                error = ex.Message.Contains("No model binder supports type");
            }
            Assert.True(error);
        }