public void GetBinder_TypeMatches_PrefixSuppressed_ReturnsFactoryInstance()
        {
            // Arrange
            int numExecutions = 0;
            IExtensibleModelBinder        theBinderInstance = new Mock <IExtensibleModelBinder>().Object;
            Func <IExtensibleModelBinder> factory           = delegate
            {
                numExecutions++;
                return(theBinderInstance);
            };

            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), factory)
            {
                SuppressPrefixCheck = true
            };
            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(string));

            // Act
            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);

            returnedBinder = provider.GetBinder(null, bindingContext);

            // Assert
            Assert.Equal(2, numExecutions);
            Assert.Equal(theBinderInstance, returnedBinder);
        }
示例#2
0
        internal static bool TryGetProviderFromAttribute(Type modelType, ModelBinderAttribute modelBinderAttribute, out ModelBinderProvider provider)
        {
            Contract.Assert(modelType != null, "modelType cannot be null.");
            Contract.Assert(modelBinderAttribute != null, "modelBinderAttribute cannot be null");

            if (typeof(ModelBinderProvider).IsAssignableFrom(modelBinderAttribute.BinderType))
            {
                // REVIEW: DI?
                provider = (ModelBinderProvider)Activator.CreateInstance(modelBinderAttribute.BinderType);
            }
            else if (typeof(IModelBinder).IsAssignableFrom(modelBinderAttribute.BinderType))
            {
                Type closedBinderType =
                    modelBinderAttribute.BinderType.IsGenericTypeDefinition
                        ? modelBinderAttribute.BinderType.MakeGenericType(modelType.GetGenericArguments())
                        : modelBinderAttribute.BinderType;

                IModelBinder binderInstance = (IModelBinder)Activator.CreateInstance(closedBinderType);
                provider = new SimpleModelBinderProvider(modelType, binderInstance)
                {
                    SuppressPrefixCheck = modelBinderAttribute.SuppressPrefixCheck
                };
            }
            else
            {
                throw Error.InvalidOperation(SRResources.ModelBinderProviderCollection_InvalidBinderType, modelBinderAttribute.BinderType, typeof(ModelBinderProvider), typeof(IModelBinder));
            }

            return(true);
        }
    public static void Register(HttpConfiguration config)
    {
        var provider = new SimpleModelBinderProvider(
            typeof(IEnumerable <int>), new CommaDelimitedArrayBinder());

        config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
    }
示例#4
0
        public static void Register(HttpConfiguration config)
        {
            var jsonFormatter = config.Formatters.OfType <JsonMediaTypeFormatter>().First();

            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver
            {
                IgnoreSerializableAttribute = true
            };

            // Web API configuration and services
            config.EnableCors(new AllowWebClientsAttribute());

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { action = "get", id = RouteParameter.Optional }
                );

            var provider = new SimpleModelBinderProvider(typeof(SubmissionRequest), new SubmitEventModelBinder());

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
        }
示例#5
0
        public static void Register(HttpConfiguration config)
        {
            var provider = new SimpleModelBinderProvider(typeof(SearchParameters), new SearchParameterModelBuilder());

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);

            config.Formatters.Add(new CsvFormatter());

            config.MapHttpAttributeRoutes();

            config.EnableCors();

            config.EnableBasicAuth();

            config.Routes.MapHttpRoute(
                name: "SearchApi",
                routeTemplate: "api/search/{search}",
                defaults: new { controller = "ApiSearch", search = RouteParameter.Optional }
                );

/*
 *          config.Routes.MapHttpRoute(
 *              name: "DefaultApi",
 *              routeTemplate: "api/{controller}/{search}",
 *              defaults: new { search = RouteParameter.Optional }
 *          );
 */

            config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Ignore
            };
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }
示例#6
0
        public static void Register(HttpConfiguration configuration)
        {
            configuration.Routes.MapHttpRoute(
                "Dashboard API",
                "api/dashboard/{action}",
                new { controller = "DashboardApi" });

            configuration.Routes.MapHttpRoute(
                "API Default",
                "api/{controller}/{action}/{parameter}",
                new { parameter = RouteParameter.Optional });

            configuration.Filters.Add(new ValidModelStateAttribute());


            var provider = new SimpleModelBinderProvider(typeof(PostDataRequest), new ArduinoDataBinder());

            configuration.Services.Insert(typeof(ModelBinderProvider), 0, provider);

            var jsonSerializerSettings = new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                ContractResolver  = new CamelCasePropertyNamesContractResolver()
            };

            configuration.Formatters.JsonFormatter.SerializerSettings = jsonSerializerSettings;
            JsonConvert.DefaultSettings = () => jsonSerializerSettings;
        }
示例#7
0
        public static void Register(HttpConfiguration config)
        {
            config.Services.Replace(typeof(ITraceWriter), new SimpleTracer());

            // Web API 路由
            var constraintResolver = new DefaultInlineConstraintResolver();

            constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint));
            config.MapHttpAttributeRoutes(constraintResolver);

            var bson = new BsonMediaTypeFormatter();

            bson.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.contoso"));
            config.Formatters.Add(bson);
            config.Formatters.Add(new ProductCsvFormatter());

            var provider = new SimpleModelBinderProvider(typeof(GeoPoint), new GeoPointModelBinder());

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
            config.Services.Add(typeof(ValueProviderFactory), new CookieValueProviderFactory());

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
示例#8
0
    public static void Register(HttpConfiguration config)
    {
        var provider = new SimpleModelBinderProvider(
            typeof(TestClass), new MyModelBinder());

        config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
        // ...
    }
        public void ModelTypeProperty()
        {
            // Arrange
            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), new Mock <IExtensibleModelBinder>().Object);

            // Act & assert
            Assert.Equal(typeof(string), provider.ModelType);
        }
示例#10
0
        private static void AddWebApiModelBinder(
            HttpConfiguration config,
            Type modelType,
            WebApi.ModelBinding.IModelBinder modelBinder)
        {
            var modelBinderProvider = new SimpleModelBinderProvider(modelType, modelBinder);

            config.Services.Insert(typeof(ModelBinderProvider), 0, modelBinderProvider);
        }
        public void GetBinderThrowsIfBindingContextIsNull()
        {
            // Arrange
            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), new Mock <IExtensibleModelBinder>().Object);

            // Act & assert
            Assert.ThrowsArgumentNull(
                delegate { provider.GetBinder(null, null); }, "bindingContext");
        }
        public static void RegisterGlobalBinders(HttpConfiguration config)
        {
            var type = typeof(DataSourceRequest);

            var modelBinder = new CustomBinders.DataSourceRequestModelBinder();

            var provider = new SimpleModelBinderProvider(type, modelBinder);

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
        }
        public void ModelBinderToString_Formats()
        {
            // Arrange
            ModelBinderProvider provider = new SimpleModelBinderProvider(typeof(int), () => null);
            string expected = typeof(SimpleModelBinderProvider).Name;

            // Act
            string actual = FormattingUtilities.ModelBinderToString(provider);

            // Assert
            Assert.Equal(expected, actual);
        }
示例#14
0
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            var provider = new SimpleModelBinderProvider(
                typeof(GetPagedListParams), new GetPagedListParamsModelBinder());

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
        }
        public void GetBinder_TypeDoesNotMatch_ReturnsNull() {
            // Arrange
            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), new Mock<IExtensibleModelBinder>().Object) {
                SuppressPrefixCheck = true
            };
            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(object));

            // Act
            IExtensibleModelBinder binder = provider.GetBinder(null, bindingContext);

            // Assert
            Assert.IsNull(binder);
        }
        public void GetBinder_TypeMatches_PrefixNotFound_ReturnsNull() {
            // Arrange
            IExtensibleModelBinder binderInstance = new Mock<IExtensibleModelBinder>().Object;
            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), binderInstance);

            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(string));
            bindingContext.ValueProvider = new SimpleValueProvider();

            // Act
            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);

            // Assert
            Assert.IsNull(returnedBinder);
        }
示例#17
0
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            foreach (var type in Filter.SupportedRangeTypes)
            {
                var intRangeProvider = new SimpleModelBinderProvider(
                    typeof(Range <>).MakeGenericType(type),
                    (IModelBinder)Activator.CreateInstance(typeof(RangeModelBinder <>).MakeGenericType(type)));

                config.Services.Insert(typeof(ModelBinderProvider), 0, intRangeProvider);
            }
        }
示例#18
0
        public void BindParameter_InsertsModelBinderProviderInPositionZero()
        {
            // Arrange
            HttpConfiguration config = new HttpConfiguration();
            Type         type        = typeof(TestParameter);
            IModelBinder binder      = new Mock <IModelBinder>().Object;

            // Act
            config.BindParameter(type, binder);

            // Assert
            SimpleModelBinderProvider provider = config.Services.GetServices(typeof(ModelBinderProvider)).OfType <SimpleModelBinderProvider>().First();

            Assert.Equal(type, provider.ModelType);
        }
        public void GetBinder_TypeDoesNotMatch_ReturnsNull()
        {
            // Arrange
            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), new Mock <IExtensibleModelBinder>().Object)
            {
                SuppressPrefixCheck = true
            };
            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(object));

            // Act
            IExtensibleModelBinder binder = provider.GetBinder(null, bindingContext);

            // Assert
            Assert.Null(binder);
        }
示例#20
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            var provider = new SimpleModelBinderProvider(
                typeof(Trade), new TradeModelBinder());

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);

            appBuilder.UseWebApi(config);
        }
        public void GetBinder_TypeMatches_PrefixSuppressed_ReturnsInstance()
        {
            // Arrange
            IExtensibleModelBinder    theBinderInstance = new Mock <IExtensibleModelBinder>().Object;
            SimpleModelBinderProvider provider          = new SimpleModelBinderProvider(typeof(string), theBinderInstance)
            {
                SuppressPrefixCheck = true
            };
            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(string));

            // Act
            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);

            // Assert
            Assert.Equal(theBinderInstance, returnedBinder);
        }
        public void GetBinder_TypeMatches_PrefixNotFound_ReturnsNull()
        {
            // Arrange
            IExtensibleModelBinder    binderInstance = new Mock <IExtensibleModelBinder>().Object;
            SimpleModelBinderProvider provider       = new SimpleModelBinderProvider(typeof(string), binderInstance);

            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(string));

            bindingContext.ValueProvider = new SimpleValueProvider();

            // Act
            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);

            // Assert
            Assert.Null(returnedBinder);
        }
示例#23
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            foreach (var type in Filter.SupportedRangeTypes)
            {
                var modelBinderProvider = new SimpleModelBinderProvider(
                    typeof(Range <>).MakeGenericType(type),
                    (IModelBinder)Activator.CreateInstance(typeof(RangeModelBinder <>).MakeGenericType(type)));

                config.Services.Insert(typeof(ModelBinderProvider), 0, modelBinderProvider);
            }

            app.UseWebApi(config);
        }
示例#24
0
        protected virtual void ConfigureWebApi(HttpConfiguration config)
        {
            // Creates the Dependency Injection Container, registers implementations,
            // and uses it for all Web API object factories (e.g. IControllerFactory.CreateController).
            // Registers an instance of SimpleInjector.Container to resolve dependencies for Web API, and returns the instance.
            var container = new Container();

            // enable property injection for filter attributes
            // see https://simpleinjector.readthedocs.io/en/2.8/registermvcattributefilterprovider-is-deprecated.html
            container.Options.PropertySelectionBehavior = new ImportPropertySelectionBehavior();

            // Make the objects per-incoming-Web-Request by default.
            container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

            // Web API Controller instances will be created by dependency injection.
            container.RegisterWebApiControllers(config);

            // Web API will use this DI container to create everything the framework knows how to inject.
            config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);

            // Usually you'd get an HttpRequestMessage from the HttpContext class in System.Web, but Web API doesn't need System.Web.
            // So we'll let Simple Injector give us access when needed.
            container.EnableHttpRequestMessageTracking(config);

            // Allow getting the Request from arbitrary code
            container.RegisterInstance <IRequestMessageAccessor>(new RequestMessageAccessor(container));

            container.RegisterMvcIntegratedFilterProvider();

            AddAppServicesToContainer(container);

            // Register a Custom Model Binder.
            var provider = new SimpleModelBinderProvider(typeof(ValidationErrorFilter), new ValidationErrorFilterModelBinder());

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);

            // Web API will use this DI container to create everything the framework knows how to inject.
            config.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);

            AddWebApiRoutes(config);
            AddResponseFormatters(config);
            AddFilters(config, container);
            config.SuppressHostPrincipal();

            container.Verify();
        }
示例#25
0
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            var provider = new SimpleModelBinderProvider(
                typeof(CustomerInputModel), new CustomerModelBinder());

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
        }
示例#26
0
        protected List <SimpleError> InvokeTest <T>(string input, string contentType = "application/x-www-form-urlencoded")
        {
            const string baseAddress = "http://dummyname/";

            string className = typeof(T).Name;

            // Server
            HttpConfiguration config = new HttpConfiguration();

            config.Routes.MapHttpRoute("Default", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            var provider = new SimpleModelBinderProvider(
                typeof(RulesetTestModel), new CustomizeValidatorAttribute {
                RuleSet = "defaults,Names"
            });

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);

            FluentValidationModelValidatorProvider.Configure(config);

            HttpServer server = new HttpServer(config);

            // Client
            HttpMessageInvoker messageInvoker = new HttpMessageInvoker(new InMemoryHttpContentSerializationHandler(server));

            //order to be created
            //			Order requestOrder = new Order() { OrderId = "A101", OrderValue = 125.00, OrderedDate = DateTime.Now.ToUniversalTime(), ShippedDate = DateTime.Now.AddDays(2).ToUniversalTime() };

            HttpRequestMessage request = new HttpRequestMessage();

            request.Content    = new StringContent(input, Encoding.UTF8, contentType);          /* JsonContent(@"{
                                                                                                 * SomeBool:'false',
                                                                                                 * Id:0}");
                                                                                                 */
            request.RequestUri = new Uri(baseAddress + "api/Test/" + className);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
            request.Method = HttpMethod.Post;

            CancellationTokenSource cts = new CancellationTokenSource();

            using (HttpResponseMessage response = messageInvoker.SendAsync(request, cts.Token).Result) {
                var errors = response.Content.ReadAsAsync <List <SimpleError> >().Result;
                return(errors);
            }
        }
示例#27
0
        /// <summary>
        /// Configuration
        /// </summary>
        /// <param name="app"></param>
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            SwaggerConfig.Register(config);
            WebApiConfig.Register(config);

            var xml = config.Formatters.XmlFormatter;

            xml.SetSerializer <PurchaseOrderType>(new XmlSerializer(typeof(PurchaseOrderType)));

            /*
             * OAuthOptions = new OAuthAuthorizationServerOptions()
             * {
             *  TokenEndpointPath = new PathString(@"/token"),
             *  Provider = new OAuthAuthorizationServerProvider()
             *  {
             *      OnValidateClientAuthentication = async (context) => context.Validated(),
             *      OnGrantResourceOwnerCredentials = async (context) =>
             *      {
             *          context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new []{"*"});
             *          if (context.UserName == "*****@*****.**" && context.Password == "P@ssw0rd")
             *          {
             *              ClaimsIdentity o = new ClaimsIdentity(context.Options.AuthenticationType);
             *              o.AddClaim(new Claim("sub", context.UserName));
             *              context.Validated(o);
             *          }
             *      }
             *  },
             *  AllowInsecureHttp = true,
             *  AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20)
             * }; */

            /*
             * app.UseOAuthBearerTokens(OAuthOptions); /* The UseOAuthBearerTokens extension method creates both the token server and the middleware to validate tokens for requests in the same application.*/

            ConfigureWindsor(config);

            var provider = new SimpleModelBinderProvider(
                typeof(PurchaseOrderType), new PurchaseOrderTypeModelBinder());

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);

            app.UseWebApi(config);
        }
        public void ModelBinderToString_With_CompositeModelBinder_Formats()
        {
            // Arrange
            ModelBinderProvider          innerProvider1    = new SimpleModelBinderProvider(typeof(int), () => null);
            ModelBinderProvider          innerProvider2    = new ArrayModelBinderProvider();
            CompositeModelBinderProvider compositeProvider = new CompositeModelBinderProvider(new ModelBinderProvider[] { innerProvider1, innerProvider2 });
            string expected = String.Format(
                "{0}({1}, {2})",
                typeof(CompositeModelBinderProvider).Name,
                typeof(SimpleModelBinderProvider).Name,
                typeof(ArrayModelBinderProvider).Name);

            // Act
            string actual = FormattingUtilities.ModelBinderToString(compositeProvider);

            // Assert
            Assert.Equal(expected, actual);
        }
示例#29
0
        public void Configuration(IAppBuilder app)
        {
            var configuration = new HttpConfiguration();

            // init formatting of JSON request/responses
            var formatters    = configuration.Formatters;
            var jsonFormatter = formatters.JsonFormatter;

            jsonFormatter.SerializerSettings.Converters.Add(new BsonDocumentJsonConverter());
            jsonFormatter.SerializerSettings.Converters.Add(new RemoteMongoQueryConverter());

            var objectIdModelBinderProvider = new SimpleModelBinderProvider(typeof(ObjectId), new ObjectIdModelBinder());

            configuration.Services.Insert(typeof(ModelBinderProvider), 0, objectIdModelBinderProvider);

            // register the DI container
            var container = UnityConfig.RegisterComponents();

            configuration.DependencyResolver = new CustomUnityDependencyResolver(container);

            // Seed the admin role
            container.Resolve <SeedRoles>().Init();

            // Enable attribute routing
            configuration.MapHttpAttributeRoutes();

            // Enable default HTTP routing
            configuration.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional });

            configuration.EnsureInitialized();

            app.UseCors(CorsOptions.AllowAll);
            app.MapSignalR(new HubConfiguration
            {
                EnableDetailedErrors = true
            });

            app.UseWebApi(configuration);
        }
示例#30
0
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
            config.Routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
            config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
            config.Routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });

            // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
            // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
            // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
            //config.EnableQuerySupport();

            // To disable tracing in your application, please comment out or remove the following line of code
            // For more information, refer to: http://www.asp.net/web-api
            //config.EnableSystemDiagnosticsTracing();

            var provider = new SimpleModelBinderProvider(typeof(KendoGridApiRequest), new KendoGridApiModelBinder());

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
        }
示例#31
0
        public void RegisterBinderForType_Instance()
        {
            // Arrange
            ModelBinderProvider    mockProvider = new Mock <ModelBinderProvider>().Object;
            IExtensibleModelBinder mockBinder   = new Mock <IExtensibleModelBinder>().Object;

            ModelBinderProviderCollection collection = new ModelBinderProviderCollection()
            {
                mockProvider
            };

            // Act
            collection.RegisterBinderForType(typeof(int), mockBinder);

            // Assert
            SimpleModelBinderProvider simpleProvider = collection[0] as SimpleModelBinderProvider;

            Assert.IsNotNull(simpleProvider, "Simple provider should've been inserted at the front of the list.");
            Assert.AreEqual(typeof(int), simpleProvider.ModelType);
            Assert.AreEqual(mockProvider, collection[1]);
        }
示例#32
0
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            config.Routes.MapHttpRoute(
                name: "ActionApi",
                routeTemplate: "api/action/{controller}/{action}/{id}/{param1}/{param2}",
                defaults: new { id = RouteParameter.Optional, param1 = RouteParameter.Optional, param2 = RouteParameter.Optional }
                );

            config.MessageHandlers.Add(new DatatableCookieHandler());

            var provider = new SimpleModelBinderProvider(typeof(JsonDatatable), new JsonDatatableBinder());

            config.Services.Insert(typeof(ModelBinderProvider), 0, provider);
        }
        public void GetBinder_TypeMatches_PrefixSuppressed_ReturnsInstance()
        {
            // Arrange
            IExtensibleModelBinder theBinderInstance = new Mock<IExtensibleModelBinder>().Object;
            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), theBinderInstance)
            {
                SuppressPrefixCheck = true
            };
            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(string));

            // Act
            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);

            // Assert
            Assert.Equal(theBinderInstance, returnedBinder);
        }
        public void GetBinderThrowsIfBindingContextIsNull()
        {
            // Arrange
            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), new Mock<IExtensibleModelBinder>().Object);

            // Act & assert
            Assert.ThrowsArgumentNull(
                delegate { provider.GetBinder(null, null); }, "bindingContext");
        }
        public void ModelTypeProperty()
        {
            // Arrange
            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), new Mock<IExtensibleModelBinder>().Object);

            // Act & assert
            Assert.Equal(typeof(string), provider.ModelType);
        }
        public void GetBinder_TypeMatches_PrefixSuppressed_ReturnsFactoryInstance()
        {
            // Arrange
            int numExecutions = 0;
            IExtensibleModelBinder theBinderInstance = new Mock<IExtensibleModelBinder>().Object;
            Func<IExtensibleModelBinder> factory = delegate
            {
                numExecutions++;
                return theBinderInstance;
            };

            SimpleModelBinderProvider provider = new SimpleModelBinderProvider(typeof(string), factory)
            {
                SuppressPrefixCheck = true
            };
            ExtensibleModelBindingContext bindingContext = GetBindingContext(typeof(string));

            // Act
            IExtensibleModelBinder returnedBinder = provider.GetBinder(null, bindingContext);
            returnedBinder = provider.GetBinder(null, bindingContext);

            // Assert
            Assert.Equal(2, numExecutions);
            Assert.Equal(theBinderInstance, returnedBinder);
        }