public static bool IsEnumPrefixFree(this ODataRoute oDataRoute)
        {
            Contract.Requires(oDataRoute != null);
            var uriResolver = oDataRoute.GetRootContainer().GetRequiredService <ODataUriResolver>();

            return(uriResolver is StringAsEnumResolver);
        }
示例#2
0
        public static TKey GetKeyFromUri <TKey>(HttpRequestMessage request, Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }

            var urlHelper = request.GetUrlHelper() ?? new UrlHelper(request);

            var        routeName  = request.ODataProperties().RouteName;
            ODataRoute oDataRoute = request.GetConfiguration().Routes[routeName] as ODataRoute;
            var        prefixName = oDataRoute.RoutePrefix;
            var        requestUri = request.RequestUri.ToString();

            string serviceRoot = requestUri.Substring(0, requestUri.IndexOf(prefixName) + prefixName.Length);

            var odataPath = request.ODataProperties().Path;

            var keySegment = odataPath.Segments.OfType <KeySegmentTemplate>().LastOrDefault().Segment.Keys.LastOrDefault();

            if (keySegment.Key == null)
            {
                throw new InvalidOperationException("The link does not contain a key.");
            }
            var value = ODataUriUtils.ConvertFromUriLiteral(keySegment.Value.ToString(), ODataVersion.V4);

            return((TKey)value);
        }
示例#3
0
        public static void RegisterDynamicOData(this HttpConfiguration config, Action <ODataServiceSettings> configureSettings)
        {
            var routeName = $"ODataService_{Guid.NewGuid().ToString("N")}";

            ODataServiceSettings settings = new ODataServiceSettings();

            BuildDefaultConfiguration(settings);

            configureSettings(settings);

            EdmModel     edmModel    = settings.Services.EdmModelBuilder(settings).GetModel();
            IDataService dataService = settings.Services.DataService(settings);

            var routingConventions = ODataRoutingConventions.CreateDefault();

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

            var oDataRoute = new ODataRoute(
                settings.RoutePrefix,
                new CustomODataPathRouteConstraint(
                    new CustomODataPathHandler(),
                    _ => edmModel,
                    routeName,
                    routingConventions,
                    dataService));

            config.Services.Insert(typeof(ModelBinderProvider), 0, new SimpleModelBinderProvider(typeof(ODataQueryOptions), new ODataQueryOptionsBinder()));
            config.Services.Insert(typeof(ModelBinderProvider), 0, new SimpleModelBinderProvider(typeof(HttpRequestMessageProperties), new ODataRequestPropertiesBinder()));
            config.Services.Insert(typeof(ModelBinderProvider), 0, new SimpleModelBinderProvider(typeof(IDataService), new DataServiceBinder()));

            config.Routes.Add(routeName, oDataRoute);
        }
示例#4
0
        /// <summary>	Registers the dynamic. </summary>
        ///
        /// <param name="config">	The configuration. </param>
        /// <param name="server">	The server. </param>
        public static async void RegisterDynamic(HttpConfiguration config, HttpServer server)
        {
            ODataRoute odataRoute = await config.MapRestierRoute <DynamicApi>(
                "DynamicApi", "api/Dynamic",
                new RestierBatchHandler(server));

            //for overriding standart metadata class
            //System.Web.OData.MetadataController
            odataRoute.PathRouteConstraint.RoutingConventions.Add(new MediadataRoutingConvention());

            // Register an Action selector that can include template parameters in the name
            IHttpActionSelector actionSelectorService = config.Services.GetActionSelector();

            config.Services.Replace(typeof(IHttpActionSelector), new DynamicODataActionSelector(actionSelectorService));
            // Register an Action invoker that can include template parameters in the name
            IHttpActionInvoker actionInvokerService = config.Services.GetActionInvoker();

            config.Services.Replace(typeof(IHttpActionInvoker), new DynamicODataActionInvoker(actionInvokerService));
            // Register an Exception handler that can include template parameters in the name
            IExceptionHandler exceptionHandler = config.Services.GetExceptionHandler();

            config.Services.Replace(typeof(IExceptionHandler), new DynamicExceptionHandler(exceptionHandler));

            // Register for Dynamic Actions
            xlsConverter.Program.ConfigureDynamicActions(config);
        }
示例#5
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);
        }
        public static string GetRoutePrefix(this ODataRoute oDataRoute)
        {
            Contract.Requires(oDataRoute != null);
            Contract.Ensures(Contract.Result <string>() != null);

            return(oDataRoute.RoutePrefix ?? string.Empty);
        }
        public static ODataRoute CustomMapODataServiceRoute(this HttpConfiguration configuration, string routeName, string routePrefix)
        {
            ODataRoute route = configuration.MapODataServiceRoute(routeName, routePrefix, builder =>
            {
                // Get the model from the datasource of the current request: model-per-request.
                builder.AddService(ServiceLifetime.Scoped, sp =>
                {
                    IHttpRequestMessageProvider requestMessageProvider = sp.GetRequiredService <IHttpRequestMessageProvider>();
                    string dataSource = requestMessageProvider.Request.Properties[Constants.ODataDataSource] as string;
                    IEdmModel model   = DataSourceProvider.GetEdmModel(dataSource);
                    return(model);
                });

                // Create a request provider for every request. This is a workaround for the missing HttpContext of a self-hosted webapi.
                builder.AddService <IHttpRequestMessageProvider>(ServiceLifetime.Scoped, sp => new HttpRequestMessageProvider());

                // The routing conventions are registered as singleton.
                builder.AddService(ServiceLifetime.Singleton, sp =>
                {
                    IList <IODataRoutingConvention> routingConventions = ODataRoutingConventions.CreateDefault();
                    routingConventions.Insert(0, new MatchAllRoutingConvention());
                    return(routingConventions.ToList().AsEnumerable());
                });
            });

            CustomODataRoute odataRoute = new CustomODataRoute(route.RoutePrefix, new CustomODataPathRouteConstraint(routeName));

            configuration.Routes.Remove(routeName);
            configuration.Routes.Add(routeName, odataRoute);

            return(odataRoute);
        }
        static void AddApiVersionConstraintIfNecessary(ODataRoute route, ApiVersioningOptions options)
        {
            Contract.Requires(route != null);
            Contract.Requires(options != null);

            var routePrefix          = route.RoutePrefix;
            var apiVersionConstraint = "{" + options.RouteConstraintName + "}";

            if (routePrefix == null || routePrefix.IndexOf(apiVersionConstraint, Ordinal) < 0 || route.Constraints.ContainsKey(options.RouteConstraintName))
            {
                return;
            }

            // note: even though the constraints are a dictionary, it's important to rebuild the entire collection
            // to make sure the api version constraint is evaluated first; otherwise, the current api version will
            // not be resolved when the odata versioning constraint is evaluated
            var originalConstraints = new Dictionary <string, object>(route.Constraints);

            route.Constraints.Clear();
            route.Constraints.Add(options.RouteConstraintName, new ApiVersionRouteConstraint());

            foreach (var constraint in originalConstraints)
            {
                route.Constraints.Add(constraint.Key, constraint.Value);
            }
        }
示例#9
0
        public void ODataVersionConstraint_DefaultValue()
        {
            var        config     = RoutingConfigurationFactory.Create();
            ODataRoute odataRoute = CreateRoute(config, routePrefix: null);

            Assert.True(((ODataVersionConstraint)odataRoute.Constraints[ODataRouteConstants.VersionConstraintName]).IsRelaxedMatch);
        }
        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);
        }
示例#11
0
        public static string GetRoutePrefix(HttpRequestMessage request)
        {
            ODataRoute oDataRoute = request.GetRouteData().Route as ODataRoute;

            Assert.NotNull(oDataRoute);

            return(oDataRoute.RoutePrefix);
        }
示例#12
0
        private static ODataPath GenerateSampleODataPath(ODataRoute oDataRoute, string sampleODataAbsoluteUri)
        {
            var oDataPathRouteConstraint = oDataRoute.GetODataPathRouteConstraint();

            var model = oDataRoute.GetEdmModel();

            return(oDataPathRouteConstraint.PathHandler.Parse(model, ServiceRoot.AppendPathSegment(oDataRoute.RoutePrefix), sampleODataAbsoluteUri));
        }
示例#13
0
        private static IEnumerable <SwaggerRoute> GenerateOperationImportRoutes(ODataRoute oDataRoute)
        {
            Contract.Requires(oDataRoute != null);

            return(oDataRoute.GetEdmModel().EntityContainer
                   .OperationImports()
                   .Select(operationImport => new SwaggerRoute(ODataSwaggerUtilities.GetPathForOperationImport(oDataRoute.RoutePrefix, operationImport), oDataRoute, ODataSwaggerUtilities.CreateSwaggerPathForOperationImport(operationImport))));
        }
示例#14
0
        private static IEnumerable <SwaggerRoute> GenerateEntityRoutes(ODataRoute oDataRoute)
        {
            Contract.Requires(oDataRoute != null);

            return(oDataRoute.GetEdmModel().EntityContainer
                   .EntitySets()
                   .Select(entitySet => new SwaggerRoute(ODataSwaggerUtilities.GetPathForEntity(oDataRoute.RoutePrefix, entitySet), oDataRoute, ODataSwaggerUtilities.CreateSwaggerPathForEntity(entitySet))));
        }
示例#15
0
        /// <summary>
        /// Maps the specified OData route and the OData route attributes.
        /// </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="configureAction">The inline method used to add Services to the ContainerBuilder based on the current RouteName.</param>
        /// <returns>The added <see cref="ODataRoute"/>.</returns>
        private static ODataRoute MapODataServiceRoute(this HttpConfiguration configuration, string routeName, string routePrefix, Action <IContainerBuilder, string> configureAction)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if (routeName == null)
            {
                throw new ArgumentNullException(nameof(routeName));
            }

            // 1) Build and configure the root container.
            var rootContainer = configuration.CreateODataRootContainer(routeName, configureAction);

            // 2) Resolve the path handler and set URI resolver to it.
            var pathHandler = rootContainer.GetRequiredService <IODataPathHandler>();

            // if settings is not on local, use the global configuration settings.
            if (pathHandler != null && pathHandler.UrlKeyDelimiter == null)
            {
                var urlKeyDelimiter = configuration.GetUrlKeyDelimiter();
                pathHandler.UrlKeyDelimiter = urlKeyDelimiter;
            }

            // 3) Resolve some required services and create the route constraint.
            var routeConstraint = new ODataPathRouteConstraint(routeName);

            // Attribute routing must initialized before configuration.EnsureInitialized is called.
            rootContainer.GetServices <IODataRoutingConvention>();

            // 4) Resolve HTTP handler, create the OData route and register it.
            ODataRoute route;
            var        routes = configuration.Routes;

            routePrefix = RemoveTrailingSlash(routePrefix);
            var messageHandler = rootContainer.GetService <HttpMessageHandler>();

            if (messageHandler != null)
            {
                route = new ODataRoute(routePrefix, routeConstraint, null, null, null, messageHandler);
            }
            else
            {
                var batchHandler = rootContainer.GetService <ODataBatchHandler>();
                if (batchHandler != null)
                {
                    batchHandler.ODataRouteName = routeName;
                    var batchTemplate = string.IsNullOrEmpty(routePrefix) ? ODataRouteConstants.Batch : routePrefix + '/' + ODataRouteConstants.Batch;
                    routes.MapHttpBatchRoute(routeName + "Batch", batchTemplate, batchHandler);
                }

                route = new ODataRoute(routePrefix, routeConstraint);
            }

            routes.Add(routeName, route);
            return(route);
        }
        public ManagementToken(ODataRoute route, DataObjectEdmModel model)
        {
            Contract.Requires <ArgumentNullException>(route != null);
            Contract.Requires <ArgumentNullException>(model != null);

            Route     = route;
            _model    = model;
            Functions = new FunctionContainer(this);
        }
示例#17
0
        public void CanGenerateDirectLink_IsFalse_IfRouteTemplateHasParameterInPrefix()
        {
            // Arrange && Act
            var        config     = RoutingConfigurationFactory.Create();
            ODataRoute odataRoute = CreateRoute(config, "{prefix}");

            // Assert
            Assert.False(odataRoute.CanGenerateDirectLink);
        }
        public static IEdmModel GetEdmModel(this ODataRoute oDataRoute)
        {
            Contract.Requires(oDataRoute != null);
            Contract.Ensures(Contract.Result <IEdmModel>() != null);

            var result = oDataRoute.GetODataPathRouteConstraint().EdmModel;

            Contract.Assume(result != null);
            return(result);
        }
示例#19
0
        public SwaggerRoute(string template, ODataRoute oDataRoute, PathItem pathItem)
        {
            Contract.Requires(!string.IsNullOrWhiteSpace(template));
            Contract.Requires(pathItem != null);
            Contract.Requires(oDataRoute != null);

            Template   = template;
            ODataRoute = oDataRoute;
            PathItem   = pathItem;
        }
        private string GetServiceRootUri()
        {
            var        routeName      = Request.ODataProperties().RouteName;
            ODataRoute odataRoute     = Configuration.Routes[routeName] as ODataRoute;
            var        prefixName     = odataRoute.RoutePrefix;
            var        requestUri     = Request.RequestUri.ToString();
            var        serviceRootUri = requestUri.Substring(0, requestUri.IndexOf(prefixName) + prefixName.Length);

            return(serviceRootUri);
        }
示例#21
0
        private static void MapOdataRoutes(HttpConfiguration config)
        {
            string routeName = "odata";

            System.Web.OData.Batch.ODataBatchHandler odataBatchHandler = new System.Web.OData.Batch.DefaultODataBatchHandler(GlobalConfiguration.DefaultServer);

            ODataRoute route = config.MapODataServiceRoute(routeName, routeName,
                                                           model: ModelConfig.GetModel(),
                                                           batchHandler: odataBatchHandler);
        }
        private static HttpConfiguration GetHttpConfiguration(this ODataRoute oDataRoute)
        {
            Contract.Requires(oDataRoute != null);
            Contract.Ensures(Contract.Result <HttpConfiguration>() != null);

            var result = RouteConfigurationTable.GetValue(oDataRoute, key => null);

            Contract.Assume(result != null);
            return(result);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataActionDescriptor"/> class.
        /// </summary>
        /// <param name="actionDescriptor">The HTTP action descriptor.</param>
        /// <param name="route">The OData route.</param>
        /// <param name="relativePathTemplate">The relative path template.</param>
        /// <param name="operation">Additional metadata based about the action.</param>
        public ODataActionDescriptor(HttpActionDescriptor actionDescriptor, ODataRoute route, string relativePathTemplate, Operation operation = null)
        {
            Contract.Requires(actionDescriptor != null);
            Contract.Requires(route != null);
            Contract.Requires(!string.IsNullOrWhiteSpace(relativePathTemplate));

            ActionDescriptor     = actionDescriptor;
            Route                = route;
            RelativePathTemplate = relativePathTemplate;
            Operation            = operation;
        }
示例#24
0
        public static IReadOnlyList<ODataRoute> MapVersionedODataRoutes(
            this HttpConfiguration configuration,
            string routeName,
            string routePrefix,
            IEnumerable<IEdmModel> models,
            IODataPathHandler pathHandler,
            IEnumerable<IODataRoutingConvention> routingConventions,
            ODataBatchHandler batchHandler )
        {
            Arg.NotNull( configuration, nameof( configuration ) );
            Arg.NotNull( models, nameof( models ) );
            Contract.Ensures( Contract.Result<IReadOnlyList<ODataRoute>>() != null );

            var routeConventions = EnsureConventions( routingConventions.ToList() );
            var routes = configuration.Routes;

            if ( !IsNullOrEmpty( routePrefix ) )
            {
                routePrefix = routePrefix.TrimEnd( '/' );
            }

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

            configuration.SetResolverSettings( pathHandler );
            routeConventions.Insert( 0, null );

            var odataRoutes = new List<ODataRoute>();
            var unversionedConstraints = new List<IHttpRouteConstraint>();

            foreach ( var model in models )
            {
                var versionedRouteName = routeName;
                var routeConstraint = default( ODataPathRouteConstraint );

                routeConventions[0] = new VersionedAttributeRoutingConvention( model, configuration );
                routeConstraint = new ODataPathRouteConstraint( pathHandler, model, versionedRouteName, routeConventions.ToArray() );
                unversionedConstraints.Add( routeConstraint );
                routeConstraint = MakeVersionedODataRouteConstraint( routeConstraint, pathHandler, routeConventions, model, ref versionedRouteName );

                var route = new ODataRoute( routePrefix, routeConstraint );

                AddApiVersionConstraintIfNecessary( route );
                routes.Add( versionedRouteName, route );
                odataRoutes.Add( route );
            }

            AddRouteToRespondWithBadRequestWhenAtLeastOneRouteCouldMatch( routeName, routePrefix, routes, odataRoutes, unversionedConstraints );

            return odataRoutes;
        }
示例#25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ODataActionDescriptor"/> class.
        /// </summary>
        /// <param name="actionDescriptor">The HTTP action descriptor.</param>
        /// <param name="route">The OData route.</param>
        /// <param name="relativePathTemplate">The relative path template.</param>
        /// <param name="operation">Additional metadata based about the action.</param>
        public ODataActionDescriptor(HttpActionDescriptor actionDescriptor, ODataRoute route, string relativePathTemplate, Operation operation = null)
        {
            Contract.Requires(actionDescriptor != null);
            Contract.Requires(route != null);
            Contract.Requires(relativePathTemplate != null);

            _actionDescriptor     = actionDescriptor;
            _route                = route;
            _relativePathTemplate = relativePathTemplate;
            _operation            = operation;
        }
示例#26
0
        /// <summary>
        /// Maps a versioned OData route. When the <paramref name="batchHandler"/> is provided, it will create a '$batch' endpoint to handle the batch requests.
        /// </summary>
        /// <param name="builder">The extended <see cref="IRouteBuilder">route builder</see>.</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 <see cref="IEdmModel">EDM model</see> to use for parsing OData paths.</param>
        /// <param name="apiVersion">The <see cref="ApiVersion">API version</see> associated with the model.</param>
        /// <param name="pathHandler">The <see cref="IODataPathHandler">OData path handler</see> to use for parsing the OData path.</param>
        /// <param name="routingConventions">The <see cref="IEnumerable{T}">sequence</see> of <see cref="IODataRoutingConvention">OData routing conventions</see>
        /// to use for controller and action selection.</param>
        /// <param name="batchHandler">The <see cref="ODataBatchHandler">OData batch handler</see>.</param>
        /// <returns>The mapped <see cref="ODataRoute">OData route</see>.</returns>
        /// <remarks>The <see cref="ApiVersionAnnotation">API version annotation</see> will be added or updated on the specified <paramref name="model"/> using
        /// the provided <paramref name="apiVersion">API version</paramref>.</remarks>
        public static ODataRoute MapVersionedODataRoute(
            this IRouteBuilder builder,
            string routeName,
            string routePrefix,
            IEdmModel model,
            ApiVersion apiVersion,
            IODataPathHandler pathHandler,
            IEnumerable <IODataRoutingConvention> routingConventions,
            ODataBatchHandler batchHandler)
        {
            Arg.NotNull(builder, nameof(builder));
            Arg.NotNullOrEmpty(routeName, nameof(routeName));
            Arg.NotNull(model, nameof(model));
            Arg.NotNull(apiVersion, nameof(apiVersion));
            Contract.Ensures(Contract.Result <ODataRoute>() != null);

            IEnumerable <IODataRoutingConvention> NewRoutingConventions(IServiceProvider serviceProvider)
            {
                var conventions = VersionedODataRoutingConventions.AddOrUpdate(routingConventions.ToList());

                conventions.Insert(0, new VersionedAttributeRoutingConvention(routeName, builder.ServiceProvider, apiVersion));
                return(conventions.ToArray());
            }

            var routeCollection          = builder.ServiceProvider.GetRequiredService <IODataRouteCollectionProvider>();
            var perRouteContainer        = builder.ServiceProvider.GetRequiredService <IPerRouteContainer>();
            var options                  = builder.ServiceProvider.GetRequiredService <ODataOptions>();
            var inlineConstraintResolver = builder.ServiceProvider.GetRequiredService <IInlineConstraintResolver>();

            if (pathHandler != null && pathHandler.UrlKeyDelimiter == null)
            {
                pathHandler.UrlKeyDelimiter = options.UrlKeyDelimiter;
            }

            model.SetAnnotationValue(model, new ApiVersionAnnotation(apiVersion));

            var configureAction = builder.ConfigureDefaultServices(container =>
                                                                   container.AddService(Singleton, typeof(IEdmModel), sp => model)
                                                                   .AddService(Singleton, typeof(IODataPathHandler), sp => pathHandler)
                                                                   .AddService(Singleton, typeof(IEnumerable <IODataRoutingConvention>), NewRoutingConventions)
                                                                   .AddService(Singleton, typeof(ODataBatchHandler), sp => batchHandler));
            var rootContainer   = perRouteContainer.CreateODataRootContainer(routeName, configureAction);
            var router          = rootContainer.GetService <IRouter>() ?? builder.DefaultHandler;
            var routeConstraint = new VersionedODataPathRouteConstraint(routeName, apiVersion);
            var route           = new ODataRoute(router, routeName, routePrefix.RemoveTrailingSlash(), routeConstraint, inlineConstraintResolver);

            builder.ConfigureBatchHandler(rootContainer, route);
            builder.Routes.Add(route);
            routeCollection.Add(new ODataRouteMapping(route, apiVersion, rootContainer));
            builder.AddRouteToRespondWithBadRequestWhenAtLeastOneRouteCouldMatch(routeName, routePrefix, apiVersion, inlineConstraintResolver);
            NotifyRoutesMapped();

            return(route);
        }
示例#27
0
        private static List <SwaggerRoute> Generate(ODataRoute oDataRoute)
        {
            var routes = new List <SwaggerRoute>();

            routes.AddRange(GenerateEntitySetRoutes(oDataRoute));
            routes.AddRange(GenerateEntityRoutes(oDataRoute));
            routes.AddRange(GenerateOperationImportRoutes(oDataRoute));
            routes.AddRange(GenerateOperationRoutes(oDataRoute));

            return(routes);
        }
示例#28
0
        protected string GetRoutePrefix()
        {
#if NETCORE
            ODataRoute oDataRoute = Request.HttpContext.GetRouteData().Routers
                                    .Where(r => r.GetType() == typeof(ODataRoute))
                                    .SingleOrDefault() as ODataRoute;
#else
            ODataRoute oDataRoute = Request.GetRouteData().Route as ODataRoute;
#endif
            Assert.NotNull(oDataRoute);
            return(oDataRoute.RoutePrefix);
        }
        /// <summary>
        /// Initialize the operations to Swagger model.
        /// </summary>
        /// <param name="oDataRoute">The o data route.</param>
        /// <returns></returns>
        private static IEnumerable <SwaggerRoute> GenerateOperationRoutes(ODataRoute oDataRoute)
        {
            Contract.Requires(oDataRoute != null);
            Contract.Requires(oDataRoute.Constraints != null);

            var routes = new List <SwaggerRoute>();

            var edmSchemaElements = oDataRoute.GetEdmModel().SchemaElements;

            if (edmSchemaElements != null)
            {
                foreach (var operation in edmSchemaElements.OfType <IEdmOperation>())
                {
                    // skip unbound operation
                    if (!operation.IsBound)
                    {
                        continue;
                    }

                    var edmOperationParameters = operation.Parameters;
                    if (edmOperationParameters != null && edmOperationParameters.Any())
                    {
                        var boundParameter = edmOperationParameters.First();
                        Contract.Assume(boundParameter != null);

                        var boundType = boundParameter.GetOperationType().GetDefinition();

                        // skip operation bound to non entity (or entity collection)
                        if (boundType.TypeKind == EdmTypeKind.Entity)
                        {
                            var entityType    = (IEdmEntityType)boundType;
                            var edmEntitySets = oDataRoute.GetEdmModel().EntityContainer.EntitySets();
                            Contract.Assume(edmEntitySets != null);
                            routes.AddRange(edmEntitySets.Where(es => es.GetEntityType().Equals(entityType)).Select(entitySet => new SwaggerRoute(ODataSwaggerUtilities.GetPathForOperationOfEntity(oDataRoute.RoutePrefix, operation, entitySet), oDataRoute, ODataSwaggerUtilities.CreateSwaggerPathForOperationOfEntity(operation, entitySet))));
                        }
                        else if (boundType.TypeKind == EdmTypeKind.Collection)
                        {
                            var collectionType = boundType as IEdmCollectionType;

                            if (collectionType?.ElementType?.GetDefinition().TypeKind == EdmTypeKind.Entity)
                            {
                                var entityType    = (IEdmEntityType)collectionType.ElementType?.GetDefinition();
                                var edmEntitySets = oDataRoute.GetEdmModel().EntityContainer.EntitySets();
                                Contract.Assume(edmEntitySets != null);
                                routes.AddRange(edmEntitySets.Where(es => es.GetEntityType().Equals(entityType)).Select(entitySet => new SwaggerRoute(ODataSwaggerUtilities.GetPathForOperationOfEntitySet(operation, entitySet, oDataRoute.RoutePrefix), oDataRoute, ODataSwaggerUtilities.CreateSwaggerPathForOperationOfEntitySet(operation, entitySet))));
                            }
                        }
                    }
                }
            }

            return(routes);
        }
        private static IList <Parameter> AddRoutePrefixParameters(ODataRoute oDataRoute)
        {
            Contract.Requires(oDataRoute != null);
            var routePrefixParameters = new List <Parameter>();
            var routePrefixTemplate   = new UriTemplate(oDataRoute.GetRoutePrefix());

            if (routePrefixTemplate.PathSegmentVariableNames.Any())
            {
                routePrefixParameters.AddRange(routePrefixTemplate.PathSegmentVariableNames.Select(pathSegmentVariableName => CreateParameter(pathSegmentVariableName, oDataRoute)));
            }
            return(routePrefixParameters);
        }