コード例 #1
0
        public void HttpRouteCollection_Dispose_UniquifiesHandlers()
        {
            // Arrange
            var collection = new HttpRouteCollection();

            var handler1 = new Mock<HttpMessageHandler>();
            handler1.Protected().Setup("Dispose", true).Verifiable();

            var handler2 = new Mock<HttpMessageHandler>();
            handler1.Protected().Setup("Dispose", true).Verifiable();

            var route1 = new Mock<IHttpRoute>();
            route1.SetupGet(r => r.Handler).Returns(handler1.Object);

            var route2 = new Mock<IHttpRoute>();
            route2.SetupGet(r => r.Handler).Returns(handler1.Object);

            var route3 = new Mock<IHttpRoute>();
            route3.SetupGet(r => r.Handler).Returns(handler2.Object);

            collection.Add("route1", route1.Object);
            collection.Add("route2", route2.Object);
            collection.Add("route3", route3.Object);

            // Act
            collection.Dispose();

            // Assert
            handler1.Protected().Verify("Dispose", Times.Once(), true);
            handler2.Protected().Verify("Dispose", Times.Once(), true);
        }
コード例 #2
0
        public static IEnumerable<ApiActionRoutingMetadata> AddHttpRoutesFromType(Type controllerType, HttpRouteCollection routes, string urlPrefix = null)
        {
            if (controllerType == null || controllerType.IsAbstract || !typeof(ApiController).IsAssignableFrom(controllerType))
            {
                yield break;
            }

            if (ControllerFilter != null && !ControllerFilter(controllerType))
            {
                yield break;
            }

            string controller = controllerType.Name.Substring(0, controllerType.Name.LastIndexOf("Controller"));
            var routingQuery = (from method in controllerType.GetMethods(BindingFlags.Instance | BindingFlags.Public)
                                let routeMaps = method.GetCustomAttributes(typeof(ApiRouteMapAttribute), false)
                                where (ControllerActionFilter == null || ControllerActionFilter(method)) && routeMaps.Length > 0
                                let meta = new ApiActionRoutingMetadata { MethodInfo = method }
                                from desc in routeMaps.Select(attr => ((ApiRouteMapAttribute)attr).CreateApiRouteDescriptor(controller, method.Name))
                                select new
                                {
                                    RouteDesc = desc,
                                    RoutingMetadata = meta
                                }).OrderByDescending(r => r.RouteDesc.Priority);

            foreach (var routing in routingQuery)
            {
                IHttpRoute httpRoute = routing.RouteDesc.CreateIHttpRoute(urlPrefix);
                string routeName = string.Format("{0}.{1}.{2}", routing.RouteDesc.Controller, routing.RouteDesc.Action, Guid.NewGuid().ToString());
                routing.RoutingMetadata.RouteTemplates.Add(httpRoute.RouteTemplate);

                // add route with ext;
                routing.RouteDesc.UrlTemplate = string.Concat(routing.RouteDesc.UrlTemplate, ".{ext}");
                routing.RouteDesc.ConstrainedParameters.Add(new ApiRouteParameterDescriptor { Name = "ext", Pattern = "json|xml" });

                IHttpRoute httpRouteWithExt = routing.RouteDesc.CreateIHttpRoute(urlPrefix);
                string routeNameWithExt = string.Concat(routeName, ".ext");
                routing.RoutingMetadata.RouteTemplates.Add(httpRouteWithExt.RouteTemplate);
                routes.Add(routeNameWithExt, httpRouteWithExt);

                // add route
                routes.Add(routeName, httpRoute);

                foreach (var mt in routing.RouteDesc.AllowedMethods)
                {
                    if (!routing.RoutingMetadata.HttpMethods.Contains(mt))
                    {
                        routing.RoutingMetadata.HttpMethods.Add(mt);
                    }
                }

                yield return routing.RoutingMetadata;
            }
        }
コード例 #3
0
        public void Descriptions_RecognizesCompositeRoutes()
        {
            var config               = new HttpConfiguration();
            var routeTemplate        = "api/values";
            var controllerDescriptor = new HttpControllerDescriptor(config, "AttributeApiExplorerValues", typeof(AttributeApiExplorerValuesController));
            var action               = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(AttributeApiExplorerValuesController).GetMethod("Action"));
            var actions              = new ReflectedHttpActionDescriptor[] { action };

            var routeCollection = new HttpRouteCollection();

            routeCollection.Add("testroute", new HttpDirectRoute(routeTemplate, actions));

            RouteCollectionRoute route = new RouteCollectionRoute();

            route.EnsureInitialized(() => routeCollection);

            config.Routes.Add("Route", route);

            var descriptions = new ApiExplorer(config).ApiDescriptions;

            ApiDescription description = Assert.Single(descriptions);

            Assert.Equal(HttpMethod.Get, description.HttpMethod);
            Assert.Equal(routeTemplate, description.RelativePath);
            Assert.Equal(action, description.ActionDescriptor);
        }
コード例 #4
0
        public void TestV08()
        {
            //var apiExplorer = new Mock<IApiExplorer>();
            //var apiDescriptions = new Collection<ApiDescription>();
            //var httpConfiguration = new HttpConfiguration();
            //var actionDescriptor =
            //	new ReflectedHttpActionDescriptor(
            //		new HttpControllerDescriptor(httpConfiguration, typeof (TestController).Name, typeof (TestController)),
            //		new TestController().GetType().GetMethod("Get"));
            //var apiDescriptionMock = new Mock<ApiDescription>();
            //apiDescriptionMock.Setup(x => x.ResponseDescription).Returns(new ResponseDescription());
            //apiDescriptionMock.Setup(x => x.ActionDescriptor).Returns(actionDescriptor);
            //apiDescriptionMock.Setup(x => x.RelativePath).Returns("test");
            //apiDescriptionMock.Setup(x => x.Route).Returns(new HttpRoute("test/{id}"));
            //apiDescriptions.Add(apiDescriptionMock.Object);
            //apiExplorer.Setup(x => x.ApiDescriptions).Returns(apiDescriptions);

            var routes = new HttpRouteCollection();

            routes.Add("test", new HttpRoute("test/{id}"));
            var conf               = new HttpConfiguration(routes);
            var apiExplorer        = conf.Services.GetApiExplorer();
            var apiExplorerService = new ApiExplorerServiceVersion08(apiExplorer, "http://test.com");
            var ramlDoc            = apiExplorerService.GetRaml(RamlVersion.Version08);

            Assert.IsNotNull(ramlDoc);
            Assert.AreEqual(RamlVersion.Version08, ramlDoc.RamlVersion);
        }
コード例 #5
0
        public static ODataRoute CustomMapODataServiceRoute(HttpRouteCollection routes, string routeName, string routePrefix, HttpMessageHandler handler = null)
        {
            if (!string.IsNullOrEmpty(routePrefix))
            {
                int prefixLastIndex = routePrefix.Length - 1;
                if (routePrefix[prefixLastIndex] == '/')
                {
                    routePrefix = routePrefix.Substring(0, routePrefix.Length - 1);
                }
            }

            var pathHandler = new DefaultODataPathHandler();

            var routingConventions = ODataRoutingConventions.CreateDefault();

            routingConventions.Insert(0, new DynamicRoutingConvention());

            var modelProvider = GetModelFuncFromRequest();

            var routeConstraint = new CustomODataPathRouteConstraint(pathHandler, modelProvider, routeName, routingConventions);

            var odataRoute = new CustomODataRoute(
                routePrefix: routePrefix,
                pathConstraint: routeConstraint,
                defaults: null,
                constraints: null,
                dataTokens: null,
                handler: handler);

            routes.Add(routeName, odataRoute);

            return(odataRoute);
        }
コード例 #6
0
        public static ODataRoute MapODataServiceRoute(this HttpRouteCollection routes, string routeName,
                                                      string routePrefix, IEdmModel model, IODataPathHandler pathHandler,
                                                      IEnumerable <IODataRoutingConvention> routingConventions, ODataBatchHandler batchHandler)
        {
            if (routes == null)
            {
                throw Error.ArgumentNull("routes");
            }

            if (!String.IsNullOrEmpty(routePrefix))
            {
                int prefixLastIndex = routePrefix.Length - 1;
                if (routePrefix[prefixLastIndex] == '/')
                {
                    // Remove the last trailing slash if it has one.
                    routePrefix = routePrefix.Substring(0, routePrefix.Length - 1);
                }
            }

            if (batchHandler != null)
            {
                batchHandler.ODataRouteName = routeName;
                string batchTemplate = String.IsNullOrEmpty(routePrefix) ? ODataRouteConstants.Batch
                    : routePrefix + '/' + ODataRouteConstants.Batch;
                routes.MapHttpBatchRoute(routeName + "Batch", batchTemplate, batchHandler);
            }

            ODataPathRouteConstraint routeConstraint =
                new ODataPathRouteConstraint(pathHandler, model, routeName, routingConventions);
            ODataRoute route = new ODataRoute(routePrefix, routeConstraint);

            routes.Add(routeName, route);
            return(route);
        }
コード例 #7
0
        public bool TryAddRoute(string routeName, string routeTemplate, IEnumerable <HttpMethod> methods, HttpRouteCollection routes, out IHttpRoute route)
        {
            route = null;

            try
            {
                var routeBuilder = CreateRouteBuilder(routeTemplate);
                var constraints  = routeBuilder.Constraints;
                if (methods != null)
                {
                    // if the methods collection is not null, apply the constraint
                    // if the methods collection is empty, we'll create a constraint
                    // that disallows ALL methods
                    constraints.Add("httpMethod", new HttpMethodConstraint(methods.ToArray()));
                }
                route = routes.CreateRoute(routeBuilder.Template, routeBuilder.Defaults, constraints);
                routes.Add(routeName, route);
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                // catch any route parsing errors
                return(false);
            }

            return(true);
        }
コード例 #8
0
        public static ODataRoute MapDynamicODataServiceRoute(
            this HttpRouteCollection routes,
            string routeName,
            string routePrefix,
            HttpServer httpServer)
        {
            IList <IODataRoutingConvention> routingConventions = ODataRoutingConventions.CreateDefault();

            routingConventions.Insert(0, new DynamicODataRoutingConvention());

            if (!string.IsNullOrEmpty(routePrefix))
            {
                int prefixLastIndex = routePrefix.Length - 1;
                if (routePrefix[prefixLastIndex] == '/')
                {
                    routePrefix = routePrefix.Substring(0, routePrefix.Length - 1);
                }
            }
            DynamicODataPathRouteConstraint routeConstraint = new DynamicODataPathRouteConstraint(
                new DefaultODataPathHandler(),
                GetModelFuncFromRequest(),
                routeName,
                routingConventions);
            DynamicODataRoute odataRoute = new DynamicODataRoute(routePrefix, routeConstraint);

            routes.Add(routeName, odataRoute);

            return(odataRoute);
        }
コード例 #9
0
		public void Test()
		{
			//var apiExplorer = new Mock<IApiExplorer>();
			//var apiDescriptions = new Collection<ApiDescription>();
			//var httpConfiguration = new HttpConfiguration();
			//var actionDescriptor =
			//	new ReflectedHttpActionDescriptor(
			//		new HttpControllerDescriptor(httpConfiguration, typeof (TestController).Name, typeof (TestController)),
			//		new TestController().GetType().GetMethod("Get"));
			//var apiDescriptionMock = new Mock<ApiDescription>();
			//apiDescriptionMock.Setup(x => x.ResponseDescription).Returns(new ResponseDescription());
			//apiDescriptionMock.Setup(x => x.ActionDescriptor).Returns(actionDescriptor);
			//apiDescriptionMock.Setup(x => x.RelativePath).Returns("test");
			//apiDescriptionMock.Setup(x => x.Route).Returns(new HttpRoute("test/{id}"));
			//apiDescriptions.Add(apiDescriptionMock.Object);
			//apiExplorer.Setup(x => x.ApiDescriptions).Returns(apiDescriptions);

			var routes = new HttpRouteCollection();
			routes.Add("test", new HttpRoute("test/{id}"));
			var conf = new HttpConfiguration(routes);
			var apiExplorer = conf.Services.GetApiExplorer();
			var apiExplorerService = new ApiExplorerService(apiExplorer, "http://test.com");
			var ramlDoc = apiExplorerService.GetRaml();
			Assert.IsNotNull(ramlDoc);
		}
コード例 #10
0
        public static ODataRoute MapODataServiceRoute(this HttpConfiguration configuration, string routeName,
                                                      string routePrefix, IEdmModel model, IODataPathHandler pathHandler,
                                                      IEnumerable <IODataRoutingConvention> routingConventions, ODataBatchHandler batchHandler)
        {
            if (configuration == null)
            {
                throw Error.ArgumentNull("configuration");
            }

            HttpRouteCollection routes = configuration.Routes;

            routePrefix = RemoveTrailingSlash(routePrefix);

            if (batchHandler != null)
            {
                batchHandler.ODataRouteName = routeName;
                string batchTemplate = String.IsNullOrEmpty(routePrefix) ? ODataRouteConstants.Batch
                    : routePrefix + '/' + ODataRouteConstants.Batch;
                routes.MapHttpBatchRoute(routeName + "Batch", batchTemplate, batchHandler);
            }

            DefaultODataPathHandler odataPathHandler = pathHandler as DefaultODataPathHandler;

            if (odataPathHandler != null)
            {
                odataPathHandler.ResolverSetttings = configuration.GetResolverSettings();
            }

            ODataPathRouteConstraint routeConstraint =
                new ODataPathRouteConstraint(pathHandler, model, routeName, routingConventions);
            ODataRoute route = new ODataRoute(routePrefix, routeConstraint);

            routes.Add(routeName, route);
            return(route);
        }
コード例 #11
0
        public void Match_ReturnsFalse_IfODataPathHasNotImplementedSegment()
        {
            // Arrange
            var request = new HttpRequestMessage(HttpMethod.Get, "http://any/Customers(1)/OpenProperty");
            HttpRouteCollection httpRouteCollection = new HttpRouteCollection();

            httpRouteCollection.Add(_routeName, new HttpRoute());
            request.SetConfiguration(new HttpConfiguration(httpRouteCollection));

            var model    = new EdmModel();
            var customer = new EdmEntityType(
                namespaceName: "NS",
                name: "Customer",
                baseType: null,
                isAbstract: false,
                isOpen: true);

            customer.AddKeys(customer.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            model.AddElement(customer);
            var container = new EdmEntityContainer("NS", "Container");

            container.AddEntitySet("Customers", customer);
            model.AddElement(container);

            var values = new Dictionary <string, object>()
            {
                { "odataPath", "Customers(1)/OpenProperty" }
            };
            var constraint = new ODataPathRouteConstraint(_pathHandler, model, _routeName, _conventions);

            // Act & Assert
            Assert.False(constraint.Match(request, null, null, values, HttpRouteDirection.UriResolution));
        }
コード例 #12
0
        public static IHttpRoute MapHttpSessionRoute(this HttpRouteCollection routes,
                                                     string name, string routeTemplate, bool readOnlySession,
                                                     object defaults = null, object constraints = null, HttpMessageHandler handler = null)
        {
            if (routes == null)
            {
                throw new ArgumentNullException(nameof(routes));
            }

            var dataTokens = new HttpRouteValueDictionary();

            if (readOnlySession)
            {
                dataTokens[Constants.EnableReadOnlySessionKey] = true;
            }
            else
            {
                dataTokens[Constants.EnableFullSessionKey] = true;
            }

            var route = routes.CreateRoute(routeTemplate, new HttpRouteValueDictionary(defaults), new HttpRouteValueDictionary(constraints), dataTokens, handler);

            routes.Add(name, route);

            return(route);
        }
 private static void MapHttpAttributeRoutesInternal(this HttpRouteCollection routes, HttpConfiguration configuration)
 {
     new RouteBuilder(configuration).BuildAllRoutes()
     .Cast <HttpAttributeRoute>()
     .ToList()
     .ForEach(r => routes.Add(r.RouteName, r));
 }
コード例 #14
0
        private static HttpRequestMessage CreateHttpRequestMessage(string requestUri)
        {
            var downloadPackageRoute = new HttpRoute(
                "api/v2/package/{id}/{version}",
                defaults: new HttpRouteValueDictionary(
                    new
            {
                controller = "Api",
                action     = "GetPackageApi",
                version    = UrlParameter.Optional
            }),
                constraints: new HttpRouteValueDictionary(
                    new
            {
                httpMethod = new HttpMethodConstraint(HttpMethod.Get)
            }));

            var routeCollection = new HttpRouteCollection();

            routeCollection.Add("v2" + RouteName.DownloadPackage, downloadPackageRoute);

            var httpConfiguration = new HttpConfiguration(routeCollection);

            var request = new HttpRequestMessage(HttpMethod.Get, requestUri);

            request.SetConfiguration(httpConfiguration);
            return(request);
        }
コード例 #15
0
        public bool TryAddRoute(string routeName, string routeTemplate, IEnumerable<HttpMethod> methods, HttpRouteCollection routes, out IHttpRoute route)
        {
            route = null;

            try
            {
                var routeBuilder = CreateRouteBuilder(routeTemplate);
                var constraints = routeBuilder.Constraints;
                if (methods != null)
                {
                    // if the methods collection is not null, apply the constraint
                    // if the methods collection is empty, we'll create a constraint
                    // that disallows ALL methods
                    constraints.Add("httpMethod", new HttpMethodConstraint(methods.ToArray()));
                }
                route = routes.CreateRoute(routeBuilder.Template, routeBuilder.Defaults, constraints);
                routes.Add(routeName, route);
            }
            catch (Exception ex) when (!ex.IsFatal()) 
            {
                // catch any route parsing errors
                return false;
            }

            return true;
        }
コード例 #16
0
        public static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints, SessionStateBehavior sessionBehavior)
        {
            var route = routes.CreateRoute(routeTemplate, defaults, constraints);

            route.SetSessionStateBehavior(sessionBehavior);
            routes.Add(name, route);

            return(route);
        }
コード例 #17
0
        /// <summary>
        /// Maps the specified route template and sets default route values and constraints.
        /// </summary>
        /// <returns>
        /// A reference to the mapped route.
        /// </returns>
        /// <param name="routes">A collection of routes for the application.</param>
        /// <param name="name">The name of the route to map.</param>
        /// <param name="routeTemplate">The route template for the route.</param>
        /// <param name="defaults">An object that contains default route values.</param>
        /// <param name="constraints">A set of expressions that specify values for routeTemplate.</param>
        public static IHttpRoute MapHttpRouteLowercase(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints)
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }
            IHttpRoute route = CreateRoute(routeTemplate, GetTypeProperties(defaults), GetTypeProperties(constraints), new Dictionary <string, object>(), null);

            routes.Add(name, route);
            return(route);
        }
コード例 #18
0
 public void Testv1()
 {
     var routes = new HttpRouteCollection();
     routes.Add("test", new HttpRoute("test/{id}"));
     var conf = new HttpConfiguration(routes);
     var apiExplorer = conf.Services.GetApiExplorer();
     var apiExplorerService = new ApiExplorerServiceVersion1(apiExplorer, "http://test.com");
     var ramlDoc = apiExplorerService.GetRaml();
     Assert.IsNotNull(ramlDoc);
     Assert.AreEqual(RamlVersion.Version1, ramlDoc.RamlVersion);
 }
コード例 #19
0
        public void should_get_null_if_request_method_does_not_match()
        {
            var routes        = new HttpRouteCollection();
            var expectedRoute = new HttpRoute("ControllerName", "ActionName", HttpMethod.Post, "resource");

            routes.Add(expectedRoute);

            HttpRoute route = routes.GetRouteData(
                new HttpRequestMessage(HttpMethod.Get, "http://www.base.com/resource"));

            Assert.Null(route);
        }
コード例 #20
0
        public static void MapFakeODataRoute(this HttpRouteCollection routes)
        {
            Mock <IHttpRoute>           mockRoute       = new Mock <IHttpRoute>();
            Mock <IHttpVirtualPathData> mockVirtualPath = new Mock <IHttpVirtualPathData>();

            mockVirtualPath.Setup(p => p.Route).Returns(mockRoute.Object);
            mockRoute.Setup(r => r.RouteTemplate).Returns("http://localhost");
            mockRoute.Setup(v => v.GetVirtualPath(
                                It.IsAny <HttpRequestMessage>(), It.IsAny <Dictionary <string, object> >())).Returns(
                mockVirtualPath.Object);
            routes.Add(RouteName, mockRoute.Object);
        }
コード例 #21
0
        public void should_get_route_if_request_uri_matches_and_constraint_matches()
        {
            var routes        = new HttpRouteCollection();
            var expectedRoute = new HttpRoute("ControllerName", "ActionName", HttpMethod.Get, "resource");

            routes.Add(expectedRoute);

            HttpRoute route = routes.GetRouteData(
                new HttpRequestMessage(HttpMethod.Get, "http://www.base.com/resource"));

            Assert.Same(expectedRoute, route);
        }
コード例 #22
0
        public static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints, HttpMessageHandler handler, string[] namespaces)
        {
            if (routes == null)
            {
                throw new ArgumentNullException("routes");
            }
            var routeValue = new HttpRouteValueDictionary(new { Namespace = namespaces });//设置路由值
            var route      = routes.CreateRoute(routeTemplate, new HttpRouteValueDictionary(defaults), new HttpRouteValueDictionary(constraints), routeValue, handler);

            routes.Add(name, route);
            return(route);
        }
コード例 #23
0
        public static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints, HttpMessageHandler handler, object dataTokens)
        {
            HttpRouteValueDictionary defaultsDictionary    = new HttpRouteValueDictionary(defaults);
            HttpRouteValueDictionary constraintsDictionary = new HttpRouteValueDictionary(constraints);
            HttpRouteValueDictionary dataTokensDictionary  = new HttpRouteValueDictionary(dataTokens);

            routeTemplate = name + "/" + routeTemplate;
            IHttpRoute route = routes.CreateRoute(routeTemplate, defaultsDictionary, constraintsDictionary, dataTokens: dataTokensDictionary, handler: handler);

            routes.Add(name, route);
            return(route);
        }
コード例 #24
0
ファイル: Program.cs プロジェクト: monsterNY/vlxm
        /// <summary>映射指定的路由模板并设置默认的路由值、约束和终结点消息处理程序。</summary>
        /// <returns>对映射路由的引用。</returns>
        /// <param name="routes">应用程序的路由的集合。</param>
        /// <param name="name">要映射的路由的名称。</param>
        /// <param name="routeTemplate">路由的路由模板。</param>
        /// <param name="defaults">一个包含默认路由值的对象。</param>
        /// <param name="constraints">一组表达式,用于指定 <paramref name="routeTemplate" /> 的值。</param>
        /// <param name="handler">请求将被调度到的处理程序。</param>
        public static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints, HttpMessageHandler handler)
        {
            if (routes == null)
            {
                throw new ArgumentNullException(nameof(routes));
            }
            HttpRouteValueDictionary routeValueDictionary1 = new HttpRouteValueDictionary(defaults);
            HttpRouteValueDictionary routeValueDictionary2 = new HttpRouteValueDictionary(constraints);
            IHttpRoute route = routes.CreateRoute(routeTemplate, (IDictionary <string, object>)routeValueDictionary1, (IDictionary <string, object>)routeValueDictionary2, (IDictionary <string, object>)null, handler);

            routes.Add(name, route);
            return(route);
        }
コード例 #25
0
        public void Testv1()
        {
            var routes = new HttpRouteCollection();

            routes.Add("test", new HttpRoute("test/{id}"));
            var conf               = new HttpConfiguration(routes);
            var apiExplorer        = conf.Services.GetApiExplorer();
            var apiExplorerService = new ApiExplorerServiceVersion1(apiExplorer, "http://test.com");
            var ramlDoc            = apiExplorerService.GetRaml();

            Assert.IsNotNull(ramlDoc);
            Assert.AreEqual(RamlVersion.Version1, ramlDoc.RamlVersion);
        }
コード例 #26
0
		public void Configure(HttpRouteCollection routeCollection)
		{
			foreach (var routeCounfiguration in Configurations)
			{
				var defaultParameters = routeCounfiguration.DefaultParameters ?? Enumerable.Empty<RouteConfigurationParameter>();

				var routeValueDictionary = BuildHttpRouteValueDictionary(defaultParameters);

				var route = new HttpRoute(routeCounfiguration.Template, routeValueDictionary);

				routeCollection.Add(routeCounfiguration.Name, route);
			}
		}
コード例 #27
0
        public static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints, params string[] namespaces)
        {
            HttpRouteValueDictionary     defaultsDictionary    = new HttpRouteValueDictionary(defaults);
            HttpRouteValueDictionary     constraintsDictionary = new HttpRouteValueDictionary(constraints);
            IDictionary <string, object> tokens = new Dictionary <string, object>()
            {
                { "Namespaces", namespaces }
            };
            IHttpRoute route = routes.CreateRoute(routeTemplate, defaultsDictionary, constraintsDictionary, tokens);

            routes.Add(name, route);
            return(route);
        }
コード例 #28
0
        public static void MapODataRout(this HttpRouteCollection routes, string name, string routePrefix, ODataConfiguration configuration)
        {
            var routeTemplate = Constants.ODataRouteTemplate;

            if (!string.IsNullOrEmpty(routePrefix) && !string.IsNullOrWhiteSpace(routePrefix))
            {
                routeTemplate = routePrefix.TrimEnd('/', '\\') + "/" + routeTemplate;
            }
            var route = new ODataRoute(routeTemplate, configuration);

            configuration.Initialize();
            routes.Add(name, route);
        }
コード例 #29
0
        private static IHttpRoute MapHttpRoute(this HttpRouteCollection routes, string name, string routeTemplate, object defaults, object constraints, string[] namespaceTokens)
        {
            HttpRouteValueDictionary     defaultsDictionary    = new HttpRouteValueDictionary(defaults);
            HttpRouteValueDictionary     constraintsDictionary = new HttpRouteValueDictionary(constraints);
            IDictionary <string, object> tokens = new Dictionary <string, object>();

            tokens.Add("Namespaces", namespaceTokens);

            IHttpRoute route = routes.CreateRoute(routeTemplate, defaultsDictionary, constraintsDictionary, dataTokens: tokens, handler: null);

            routes.Add(name, route);

            return(route);
        }
コード例 #30
0
        /// <summary>
        /// Maps the specified OData route. When the <paramref name="defaultHandler"/> is non-<c>null</c>, it will map
        /// it as the handler for the route.
        /// </summary>
        /// <param name="configuration">The server configuration.</param>
        /// <param name="routeName">The name of the route to map.</param>
        /// <param name="routePrefix">The prefix to add to the OData route's path template.</param>
        /// <param name="model">The EDM model to use for parsing OData paths.</param>
        /// <param name="pathHandler">The <see cref="IODataPathHandler" /> to use for parsing the OData path.</param>
        /// <param name="routingConventions">
        /// The OData routing conventions to use for controller and action selection.
        /// </param>
        /// <param name="defaultHandler">The default <see cref="HttpMessageHandler"/> for this route.</param>
        /// <returns>The added <see cref="ODataRoute"/>.</returns>
        public static ODataRoute MapODataServiceRoute(this HttpConfiguration configuration, string routeName,
                                                      string routePrefix, IEdmModel model, IODataPathHandler pathHandler,
                                                      IEnumerable <IODataRoutingConvention> routingConventions, HttpMessageHandler defaultHandler)
        {
            if (configuration == null)
            {
                throw Error.ArgumentNull("configuration");
            }

            // We have a more specific overload to map batch handlers that creates a different route for the batch
            // endpoint instead of mapping that handler as the per route handler. Given that HttpMessageHandler is a
            // base type of ODataBatchHandler, it's possible the compiler will call this overload instead of the one
            // for the batch handler, so we detect that case and call the appropiate overload for the user.
            // The case in which the compiler picks the wrong overload is:
            // HttpRequestMessageHandler batchHandler = new DefaultODataBatchHandler(httpServer);
            // config.Routes.MapODataServiceRoute("routeName", "routePrefix", model, batchHandler);
            if (defaultHandler != null)
            {
                ODataBatchHandler batchHandler = defaultHandler as ODataBatchHandler;
                if (batchHandler != null)
                {
                    return(MapODataServiceRoute(configuration, routeName, routePrefix, model, batchHandler));
                }
            }

            HttpRouteCollection routes = configuration.Routes;

            routePrefix = RemoveTrailingSlash(routePrefix);

            DefaultODataPathHandler odataPathHandler = pathHandler as DefaultODataPathHandler;

            if (odataPathHandler != null)
            {
                odataPathHandler.ResolverSetttings = configuration.GetResolverSettings();
            }

            ODataPathRouteConstraint routeConstraint =
                new ODataPathRouteConstraint(pathHandler, model, routeName, routingConventions);
            ODataRoute route = new ODataRoute(
                routePrefix,
                routeConstraint,
                defaults: null,
                constraints: null,
                dataTokens: null,
                handler: defaultHandler);

            routes.Add(routeName, route);
            return(route);
        }
コード例 #31
0
        public static IHttpRoute MapODataServiceBatchRoute(this HttpRouteCollection routes, string name,
                                                           string routeTemplate,
                                                           object defaults, object constraints,
                                                           HttpMessageHandler handler)
        {
            var route = routes.CreateRoute(routeTemplate, new HttpRouteValueDictionary(defaults),
                                           new HttpRouteValueDictionary(constraints),
                                           new HttpRouteValueDictionary()
            {
                { "RouteId", name }
            },
                                           handler);

            routes.Add(name, route);
            return(route);
        }
コード例 #32
0
        public void Match_ReturnsFalse_IfODataPathCannotBeParsed()
        {
            // Arrange
            var request = new HttpRequestMessage(HttpMethod.Get, "http://any/NotAnODataPath");
            HttpRouteCollection httpRouteCollection = new HttpRouteCollection();
            httpRouteCollection.Add(_routeName, new HttpRoute());
            var configuration = new HttpConfiguration(httpRouteCollection);
            configuration.EnableODataDependencyInjectionSupport(_routeName);
            request.SetConfiguration(configuration);

            var values = new Dictionary<string, object>() { { "odataPath", "NotAnODataPath" } };
            var constraint = CreatePathRouteConstraint();

            // Act & Assert
            Assert.False(constraint.Match(request, null, null, values, HttpRouteDirection.UriResolution));
        }
コード例 #33
0
        static void ApiRoute(HttpRouteCollection routes, string url, [AspMvcController] string controller, [AspMvcAction] string action)
        {
            url = String.Format("{0}/{1}", ConstantStrings.WebApiExecutionPath, url);
            HttpRouteValueDictionary defaults = new HttpRouteValueDictionary();

            if (controller != null)
            {
                defaults["controller"] = controller;
            }
            if (action != null)
            {
                defaults["action"] = action;
            }
            IHttpRoute route = routes.CreateRoute(url, defaults, new Dictionary <string, object>());

            routes.Add(route.RouteTemplate, route);
        }
コード例 #34
0
        // Add generation hooks for the Attribute-routing subroutes.
        // This lets us generate urls for routes supplied by attr-based routing.
        private static void AddGenerationHooksForSubRoutes(HttpRouteCollection routeTable,
                                                           IEnumerable <RouteEntry> entries)
        {
            Contract.Assert(entries != null);
            foreach (RouteEntry entry in entries)
            {
                Contract.Assert(entry != null);
                string name = entry.Name;

                if (name != null)
                {
                    IHttpRoute route = entry.Route;
                    Contract.Assert(route != null);
                    IHttpRoute linkGenerationRoute = new LinkGenerationRoute(route);
                    routeTable.Add(name, linkGenerationRoute);
                }
            }
        }
コード例 #35
0
        // Add generation hooks for the Attribute-routing subroutes. 
        // This lets us generate urls for routes supplied by attr-based routing.
        private static void AddGenerationHooksForSubRoutes(HttpRouteCollection routeTable,
            IEnumerable<RouteEntry> entries)
        {
            Contract.Assert(entries != null);
            foreach (RouteEntry entry in entries)
            {
                Contract.Assert(entry != null);
                string name = entry.Name;

                if (name != null)
                {
                    IHttpRoute route = entry.Route;
                    Contract.Assert(route != null);
                    IHttpRoute linkGenerationRoute = new LinkGenerationRoute(route);
                    routeTable.Add(name, linkGenerationRoute);
                }
            }
        }
コード例 #36
0
ファイル: Program.cs プロジェクト: monsterNY/vlxm
 /// <summary>忽略指定的路由。</summary>
 /// <returns>返回 <see cref="T:System.Web.Http.Routing.IHttpRoute" />。</returns>
 /// <param name="routes">应用程序的路由的集合。</param>
 /// <param name="routeName">要忽略的路由的名称。</param>
 /// <param name="routeTemplate">路由的路由模板。</param>
 /// <param name="constraints">一组表达式,用于指定路由模板的值。</param>
 public static IHttpRoute IgnoreRoute(this HttpRouteCollection routes, string routeName, string routeTemplate, object constraints)
 {
     if (routes == null)
     {
         throw new ArgumentNullException(nameof(routes));
     }
     if (routeName == null)
     {
         throw new ArgumentNullException(nameof(routeName));
     }
     if (routeTemplate == null)
     {
         throw new ArgumentNullException(nameof(routeTemplate));
     }
     HttpRouteCollectionExtensions.IgnoreHttpRouteInternal httpRouteInternal = new HttpRouteCollectionExtensions.IgnoreHttpRouteInternal(routeTemplate, new HttpRouteValueDictionary(constraints), (HttpMessageHandler) new StopRoutingHandler());
     routes.Add(routeName, (IHttpRoute)httpRouteInternal);
     return((IHttpRoute)httpRouteInternal);
 }
コード例 #37
0
        public void Match_ReturnsFalse_IfODataPathCannotBeParsed()
        {
            // Arrange
            var request = new HttpRequestMessage(HttpMethod.Get, "http://any/NotAnODataPath");
            HttpRouteCollection httpRouteCollection = new HttpRouteCollection();

            httpRouteCollection.Add(_routeName, new HttpRoute());
            request.SetConfiguration(new HttpConfiguration(httpRouteCollection));

            var values = new Dictionary <string, object>()
            {
                { "odataPath", "NotAnODataPath" }
            };
            var constraint = new ODataPathRouteConstraint(_pathHandler, _model, _routeName, _conventions);

            // Act & Assert
            Assert.False(constraint.Match(request, null, null, values, HttpRouteDirection.UriResolution));
        }
コード例 #38
0
        private static ODataRoute CustomMapODataServiceRoute(
            HttpRouteCollection routes,
            string routeName,
            string routePrefix,
            Func<HttpRequestMessage, IEdmModel> modelProvider,
            IODataPathHandler pathHandler,
            IEnumerable<IODataRoutingConvention> routingConventions,
            ODataBatchHandler batchHandler)
        {
            if (!string.IsNullOrEmpty(routePrefix))
            {
                int prefixLastIndex = routePrefix.Length - 1;
                if (routePrefix[prefixLastIndex] == '/')
                {
                    routePrefix = routePrefix.Substring(0, routePrefix.Length - 1);
                }
            }

            if (batchHandler != null)
            {
                batchHandler.ODataRouteName = routeName;
                string batchTemplate = string.IsNullOrEmpty(routePrefix)
                    ? ODataRouteConstants.Batch
                    : routePrefix + '/' + ODataRouteConstants.Batch;
                routes.MapHttpBatchRoute(routeName + "Batch", batchTemplate, batchHandler);
            }

            CustomODataPathRouteConstraint routeConstraint = new CustomODataPathRouteConstraint(
                pathHandler,
                modelProvider,
                routeName,
                routingConventions);
            CustomODataRoute odataRoute = new CustomODataRoute(routePrefix, routeConstraint);
            routes.Add(routeName, odataRoute);

            return odataRoute;
        }
コード例 #39
0
        /// <summary>
        /// Builds the contents for the route table based on the attributes
        /// found on a specific controller type.
        /// </summary>
        /// <param name="routes"></param>
        /// <param name="controllerType"></param>
        private static void BuildControllerRoutes(HttpRouteCollection routes, Type controllerType)
        {
            var attributes = (HttpRouteAttribute[]) controllerType.GetCustomAttributes(typeof(HttpRouteAttribute), true);

            string controller = controllerType.Name;

            // Translate the somewhat weird controller name into one the routing system
            // understands, by removing the Controller part from the name.
            if (controller.EndsWith("Controller", StringComparison.Ordinal))
            {
                controller = controller.Substring(0, controller.IndexOf("Controller"));
            }

            foreach (var attribute in attributes)
            {
                var routeValuesDictionary = new HttpRouteValueDictionary();
                routeValuesDictionary.Add("controller", controller);

                // Create the route and attach the default route handler to it.
                var route = new HttpRoute(attribute.UriTemplate, routeValuesDictionary, new HttpRouteValueDictionary(), new HttpRouteValueDictionary());

                routes.Add(Guid.NewGuid().ToString(), route);
            }
        }
コード例 #40
0
        public void Match_ReturnsFalse_IfODataPathHasNotImplementedSegment()
        {
            // Arrange
            var request = new HttpRequestMessage(HttpMethod.Get, "http://any/Customers/$count");
            HttpRouteCollection httpRouteCollection = new HttpRouteCollection();
            httpRouteCollection.Add(_routeName, new HttpRoute());
            request.SetConfiguration(new HttpConfiguration(httpRouteCollection));

            var values = new Dictionary<string, object>() { { "odataPath", "Customers/$count" } };
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Customer>("Customers");
            IEdmModel model = builder.GetEdmModel();
            var constraint = new ODataPathRouteConstraint(_pathHandler, model, _routeName, _conventions);

            // Act & Assert
            Assert.False(constraint.Match(request, null, null, values, HttpRouteDirection.UriResolution));
        }
コード例 #41
0
        public void Match_ReturnsFalse_IfODataPathCannotBeParsed()
        {
            // Arrange
            var request = new HttpRequestMessage(HttpMethod.Get, "http://any/NotAnODataPath");
            HttpRouteCollection httpRouteCollection = new HttpRouteCollection();
            httpRouteCollection.Add(_routeName, new HttpRoute());
            request.SetConfiguration(new HttpConfiguration(httpRouteCollection));

            var values = new Dictionary<string, object>() { { "odataPath", "NotAnODataPath" } };
            var constraint = new ODataPathRouteConstraint(_pathHandler, _model, _routeName, _conventions);

            // Act & Assert
            Assert.False(constraint.Match(request, null, null, values, HttpRouteDirection.UriResolution));
        }
コード例 #42
0
        public void Match_ReturnsTrue_IfODataPathCanBeParsed()
        {
            // Arrange
            var request = new HttpRequestMessage(HttpMethod.Get, "http://any/odata/$metadata");
            HttpRouteCollection httpRouteCollection = new HttpRouteCollection();
            httpRouteCollection.Add(_routeName, new HttpRoute());
            request.SetConfiguration(new HttpConfiguration(httpRouteCollection));

            var values = new Dictionary<string, object>() { { "odataPath", "$metadata" } };
            var constraint = new ODataPathRouteConstraint(_pathHandler, _model, _routeName, _conventions);

            // Act & Assert
            Assert.True(constraint.Match(request, null, null, values, HttpRouteDirection.UriResolution));

            Assert.Equal("Metadata", values["controller"]);
            Assert.Same(_model, request.ODataProperties().Model);
            Assert.Same(_routeName, request.ODataProperties().RouteName);
            Assert.Equal(_conventions, request.ODataProperties().RoutingConventions);
            Assert.Same(_pathHandler, request.ODataProperties().PathHandler);
        }
コード例 #43
0
        public void Descriptions_RecognizesCompositeRoutes()
        {
            var config = new HttpConfiguration();
            var routeTemplate = "api/values";
            var controllerDescriptor = new HttpControllerDescriptor(config, "AttributeApiExplorerValues", typeof(AttributeApiExplorerValuesController));
            var action = new ReflectedHttpActionDescriptor(controllerDescriptor, typeof(AttributeApiExplorerValuesController).GetMethod("Action"));
            var actions = new ReflectedHttpActionDescriptor[] { action };

            var routeCollection = new HttpRouteCollection();
            routeCollection.Add("testroute", new HttpDirectRoute(routeTemplate, actions));

            RouteCollectionRoute route = new RouteCollectionRoute();
            route.EnsureInitialized(() => routeCollection);

            config.Routes.Add("Route", route);

            var descriptions = new ApiExplorer(config).ApiDescriptions;

            ApiDescription description = Assert.Single(descriptions);
            Assert.Equal(HttpMethod.Get, description.HttpMethod);
            Assert.Equal(routeTemplate, description.RelativePath);
            Assert.Equal(action, description.ActionDescriptor);
        }
コード例 #44
0
        public void Match_ReturnsFalse_IfODataPathHasNotImplementedSegment()
        {
            // Arrange
            var request = new HttpRequestMessage(HttpMethod.Get, "http://any/Customers(1)/OpenProperty");
            HttpRouteCollection httpRouteCollection = new HttpRouteCollection();
            httpRouteCollection.Add(_routeName, new HttpRoute());
            request.SetConfiguration(new HttpConfiguration(httpRouteCollection));

            var model = new EdmModel();
            var customer = new EdmEntityType(
                namespaceName: "NS",
                name: "Customer",
                baseType: null,
                isAbstract: false,
                isOpen: true);
            customer.AddKeys(customer.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32));
            model.AddElement(customer);
            var container = new EdmEntityContainer("NS", "Container");
            container.AddEntitySet("Customers", customer);
            model.AddElement(container);

            var values = new Dictionary<string, object>() { { "odataPath", "Customers(1)/OpenProperty" } };
            var constraint = new ODataPathRouteConstraint(_pathHandler, model, _routeName, _conventions);

            // Act & Assert
            Assert.False(constraint.Match(request, null, null, values, HttpRouteDirection.UriResolution));
        }
コード例 #45
0
        private static HttpRouteCollection MapHttpAttributeRoutesInternal(this HttpConfiguration configuration, HttpRouteBuilder routeBuilder)
        {
            HttpRouteCollection subRoutes = new HttpRouteCollection();

            if (configuration == null)
            {
                throw Error.ArgumentNull("configuration");
            }

            if (routeBuilder == null)
            {
                throw Error.ArgumentNull("routeBuilder");
            }

            List<HttpRouteEntry> attributeRoutes = new List<HttpRouteEntry>();

            IHttpControllerSelector controllerSelector = configuration.Services.GetHttpControllerSelector();
            IDictionary<string, HttpControllerDescriptor> controllerMap = controllerSelector.GetControllerMapping();
            if (controllerMap != null)
            {
                foreach (HttpControllerDescriptor controllerDescriptor in controllerMap.Values)
                {
                    IEnumerable<HttpRouteEntry> controllerRoutes = CreateRouteEntries(controllerDescriptor);

                    foreach (HttpRouteEntry route in controllerRoutes)
                    {
                        route.Route = routeBuilder.BuildHttpRoute(route.RouteTemplate, route.Actions);
                    }

                    SetDefaultRouteNames(controllerRoutes, controllerDescriptor.ControllerName);
                    attributeRoutes.AddRange(controllerRoutes);
                }

                attributeRoutes.Sort();

                foreach (HttpRouteEntry attributeRoute in attributeRoutes)
                {
                    IHttpRoute route = attributeRoute.Route;
                    if (route != null)
                    {
                        subRoutes.Add(attributeRoute.Name, attributeRoute.Route);
                    }
                }
            }

            return subRoutes;
        }
コード例 #46
0
 // Add generation hooks for the Attribute-routing subroutes. 
 // This lets us generate urls for routes supplied by attr-based routing.
 private static void AddGenerationHooksForSubRoutes(HttpRouteCollection destRoutes, HttpRouteCollection sourceRoutes)
 {
     foreach (KeyValuePair<string, IHttpRoute> kv in sourceRoutes.GetRoutesWithNames())
     {
         string name = kv.Key;
         IHttpRoute route = kv.Value;
         var stubRoute = new GenerateRoute(route);
         destRoutes.Add(name, stubRoute);
     }
 }
コード例 #47
0
        /// <summary>
        /// Builds the contents for the route table based on the attributes
        /// found on the method of a specific controller.
        /// </summary>
        /// <param name="routes"></param>
        /// <param name="controllerType"></param>
        /// <param name="method"></param>
        private static void BuildControllerMethodRoutes(HttpRouteCollection routes, Type controllerType, MethodInfo method)
        {
            // Grab the http route attributes from the current method.
            var attributes = (HttpRouteAttribute[]) method.GetCustomAttributes(typeof(HttpRouteAttribute), true);

            if (attributes.Length != 0)
            {
                // Automatically grab the controller name and action name
                // from the method and controller type.
                string action = method.Name;
                string controller = controllerType.Name;

                // Translate the somewhat weird controller name into one the routing system
                // understands, by removing the Controller part from the name.
                if (controller.EndsWith("Controller", StringComparison.Ordinal))
                {
                    controller = controller.Substring(0, controller.IndexOf("Controller"));
                }

                // Generate a route for every HTTP route attribute found on the method
                foreach (var attribute in attributes)
                {
                    var routeValueDictionary = new HttpRouteValueDictionary();

                    routeValueDictionary.Add("controller", controller);
                    routeValueDictionary.Add("action", action);

                    ResolveOptionalRouteParameters(attribute.UriTemplate, method, routeValueDictionary);

                    // Create the route and attach the default route handler to it.
                    var route = new HttpRoute(attribute.UriTemplate, routeValueDictionary, new HttpRouteValueDictionary(), new HttpRouteValueDictionary());

                    routes.Add(Guid.NewGuid().ToString(), route);
                }
            }
        }
コード例 #48
0
 // Add generation hooks for the Attribute-routing subroutes. 
 // This lets us generate urls for routes supplied by attr-based routing.
 private static void AddGenerationHooksForSubRoutes(HttpRouteCollection destRoutes, HttpSubRouteCollection sourceRoutes, HttpRouteBuilder routeBuilder)
 {
     foreach (KeyValuePair<string, IHttpRoute> kv in sourceRoutes.NamedRoutes)
     {
         string name = kv.Key;
         IHttpRoute route = kv.Value;
         var stubRoute = routeBuilder.BuildGenerationRoute(route);
         destRoutes.Add(name, stubRoute);
     }
 }