public HttpControllerContext(HttpConfiguration configuration, IHttpRouteData routeData,
            HttpRequestMessage request)
        {
            if (configuration == null)
            {
                throw Error.ArgumentNull("configuration");
            }

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

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

            _requestContext = new HttpRequestContext
            {
                Configuration = configuration,
                RouteData = routeData
            };
            _request = request;
        }
 internal static IEnumerable<KeyValuePair<string, string>> GetRoutes(IHttpRouteData routeData)
 {
     foreach (KeyValuePair<string, object> pair in routeData.Values)
     {
         yield return new KeyValuePair<string, string>(pair.Key, pair.Value.ToString());
     }
 }
Esempio n. 3
0
        protected RouteTest(string url, HttpMethod httpMethod)
        {
            HttpRequestMessage = new HttpRequestMessage(httpMethod, url);
            HttpRequestMessage.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, GlobalConfiguration.Configuration);


           // if (HttpRequestMessage == null)

            foreach (IHttpRoute httpRoute in GlobalConfiguration.Configuration.Routes)

                //GlobalConfiguration.Configuration.Routes.VirtualPathRoot = "sdf";
            {

         
                IHttpRouteData routeData = httpRoute.GetRouteData("http://test.com/", HttpRequestMessage);
                if (routeData != null)
                {
                    var d = routeData;
                }
            }
            var r = (IHttpRouteData)null;


           
            var route = new HttpRouteData(new HttpRoute());
            HttpRouteData = GlobalConfiguration.Configuration.Routes.GetRouteData(HttpRequestMessage);
            HttpRequestMessage.Properties[HttpPropertyKeys.HttpRouteDataKey] = HttpRouteData;
            ControllerSelector = new DefaultHttpControllerSelector(GlobalConfiguration.Configuration);
            ControllerContext = new HttpControllerContext(GlobalConfiguration.Configuration, HttpRouteData, HttpRequestMessage);
        }
 private static void AddLinkInfoToRouteData(IHttpRouteData routeData, ODataPath odataPath)
 {
     KeyValuePathSegment keyValueSegment = odataPath.Segments[1] as KeyValuePathSegment;
     routeData.Values[ODataRouteConstants.Key] = keyValueSegment.Value;
     NavigationPathSegment navigationSegment = odataPath.Segments[3] as NavigationPathSegment;
     routeData.Values[ODataRouteConstants.NavigationProperty] = navigationSegment.NavigationProperty.Name;
 }
 internal static IEnumerable<KeyValuePair<string, string>> GetRouteValues(IHttpRouteData routeData)
 {
     foreach (KeyValuePair<string, object> pair in routeData.Values)
     {
         string value = (pair.Value == null) ? null : pair.Value.ToString();
         yield return new KeyValuePair<string, string>(pair.Key, value);
     }
 }
        private string GetKeyFromRouteData(IHttpRouteData routeData)
        {
            var subRouteData = routeData.GetSubRoutes().FirstOrDefault();
            if (subRouteData == null) return null;

            var httpActionDescriptors = (HttpActionDescriptor[])subRouteData.Route.DataTokens["actions"];
            return httpActionDescriptors.First().ControllerDescriptor.ControllerType.FullName.ToLowerInvariant();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpControllerHandler"/> class.
        /// </summary>
        /// <param name="routeData">The route data.</param>
        public HttpControllerHandler(RouteData routeData)
        {
            if (routeData == null)
            {
                throw Error.ArgumentNull("routeData");
            }

            _routeData = new HostedHttpRouteData(routeData);
        }
 public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration, IHttpRouteData routeData, HttpRequestMessage request)
 {
     HttpConfiguration config = configuration ?? new HttpConfiguration();
     IHttpRouteData route = routeData ?? new HttpRouteData(new HttpRoute());
     HttpRequestMessage req = request ?? new HttpRequestMessage();
     req.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
     req.Properties[HttpPropertyKeys.HttpRouteDataKey] = route;
     return new HttpControllerContext(config, route, req);
 }
 private void Dispose(IHttpRouteData routeData, string key)
 {
     IDisposable elapsed = (IDisposable)routeData.Values.TryGetC(key);
     if (elapsed != null)
     {
         elapsed.Dispose();
         routeData.Values.Remove(key);
     }
 }
 public ControllerActionSelector(HttpConfiguration conf, HttpRequestMessage req)
 {
     config = conf;
     request = req;
     routeData = config.Routes.GetRouteData(request);
     request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData;
     controllerSelector = new DefaultHttpControllerSelector(config);
     controllerContext = new HttpControllerContext(config, routeData, request);
 }
Esempio n. 11
0
 public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration, IHttpRouteData routeData, HttpRequestMessage request)
 {
     HttpConfiguration config = configuration ?? new HttpConfiguration();
     IHttpRouteData route = routeData ?? new HttpRouteData(new HttpRoute());
     HttpRequestMessage req = request ?? new HttpRequestMessage();
     req.SetConfiguration(config);
     req.SetRouteData(route);
     return new HttpControllerContext(config, route, req) { ControllerDescriptor = new HttpControllerDescriptor(config) };
 }
 private static void AddLinkInfoToRouteData(IHttpRouteData routeData, ODataPath odataPath)
 {
     KeyValuePathSegment keyValueSegment = odataPath.Segments.OfType<KeyValuePathSegment>().First();
     routeData.Values[ODataRouteConstants.Key] = keyValueSegment.Value;
     KeyValuePathSegment relatedKeySegment = odataPath.Segments.Last() as KeyValuePathSegment;
     if (relatedKeySegment != null)
     {
         routeData.Values[ODataRouteConstants.RelatedKey] = relatedKeySegment.Value;
     }
 }
        internal static NameValueCollection GetRoutes(IHttpRouteData routeData)
        {
            //// REVIEW: better way to map KeyValuePairs into NameValueCollection
            NameValueCollection nameValueCollection = new NameValueCollection();
            foreach (KeyValuePair<string, object> pair in routeData.Values)
            {
                nameValueCollection.Add(pair.Key, pair.Value.ToString());
            }

            return nameValueCollection;
        }
        /// <summary>
        /// Gets the requested controller version from routing data
        /// </summary>
        /// <param name="routeData"></param>
        /// <returns></returns>
        protected virtual ApiVersion GetControllerVersionFromRouteData(IHttpRouteData routeData) {
            string rawVersionNumber = this.GetStringRouteValue(routeData, this.RouteKey);

            if (rawVersionNumber == null) {
                return null;
            }

            Version versionNumber = ParseVersionNumber(rawVersionNumber);

            return new SemVerApiVersion(versionNumber);
        }
        private static int GetOrderKey(
            IHttpRouteData routeData, Uri requestUri)
        {
            object orderKeyString;
            if (routeData.Values.TryGetValue("key", out orderKeyString)) {

                return int.Parse(orderKeyString.ToString());
            }

            // It's now sure that query string has the shipmentKey value
            var quesryString = requestUri.ParseQueryString();
            return int.Parse(quesryString["key"]);
        }
        private static HttpControllerDescriptor GetVersionedRouteController(IHttpRouteData routeData, string versionText)
        {
            HttpControllerDescriptor httpControllerDescriptor = null;
            CandidateAction[] candidates = routeData.GetDirectRouteCandidates();
            var version = NuGetVersion.Parse(versionText);
            if (candidates != null)
            {
                //闭包
                SemanticVersionedAttribute semanticVersionedAttribute = null;
                var q = candidates
                            .Where
                                (
                                    (x) =>
                                    {
                                        var rr = false;
                                        //闭包
                                        semanticVersionedAttribute = x
                                                        .ActionDescriptor
                                                        .GetCustomAttributes<SemanticVersionedAttribute>()
                                                        .FirstOrDefault();
                                        if (semanticVersionedAttribute != null)
                                        {
                                            //rr = semanticVersionedAttribute
                                            //            .AllowedVersionRange
                                            //            .Satisfies(version);

                                            rr = true;
                                        }
                                        return rr;
                                    }
                                );
                q = q.OrderByDescending
                    (
                        (x) =>
                        {
                            return
                                     x
                                        .ActionDescriptor
                                        .GetCustomAttributes<SemanticVersionedAttribute>()
                                        .First()
                                        .Version;
                        }
                        , new VersionComparer()
                    );
                httpControllerDescriptor = q
                                            .First()
                                            .ActionDescriptor
                                            .ControllerDescriptor;
            }
            return httpControllerDescriptor;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpControllerHandler"/> class.
        /// </summary>
        /// <param name="routeData">The route data.</param>
        /// <param name="handler">The message handler to dispatch requests to.</param>
        public HttpControllerHandler(RouteData routeData, HttpMessageHandler handler)
        {
            if (routeData == null)
            {
                throw Error.ArgumentNull("routeData");
            }
            if (handler == null)
            {
                throw Error.ArgumentNull("handler");
            }

            _routeData = new HostedHttpRouteData(routeData);
            _server = new HttpMessageInvoker(handler);
        }
Esempio n. 18
0
        public static HttpControllerContext CreateControllerContext(IHttpController instance, string controllerName, Type controllerType, HttpConfiguration configuration = null, IHttpRouteData routeData = null, HttpRequestMessage request = null)
        {
            HttpConfiguration config = configuration ?? new HttpConfiguration();
            IHttpRouteData route = routeData ?? new HttpRouteData(new HttpRoute());
            HttpRequestMessage req = request ?? new HttpRequestMessage();
            req.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            req.Properties[HttpPropertyKeys.HttpRouteDataKey] = route;

            HttpControllerContext context = new HttpControllerContext(config, route, req);
            context.Controller = instance;
            context.ControllerDescriptor = CreateControllerDescriptor(controllerName, controllerType, config);

            return context;
        }
        private static Guid GetShipmentKey(IHttpRouteData routeData, Uri requestUri) {

            // We are sure at this point that the shipmentKey value has been
            // supplied (either through route or quesry string) because it 
            // wouldn't be possible for the request to arrive here if it wasn't.
            object shipmentKeyString;
            if (routeData.Values.TryGetValue("shipmentKey", out shipmentKeyString)) {

                return Guid.ParseExact(shipmentKeyString.ToString(), "D");
            }

            // It's now sure that query string has the shipmentKey value
            var quesryString = requestUri.ParseQueryString();
            return Guid.ParseExact(quesryString["shipmentKey"], "D");
        }
        /// <summary>
        /// Parses a raw version number from the routing key
        /// </summary>
        /// <returns></returns>
        protected string GetStringRouteValue(IHttpRouteData routeData, string routeKey) {
            // Look up controller in route data
            object controllerVersion;
            if (!routeData.Values.TryGetValue(routeKey, out controllerVersion)) {
                const string msg = "Cannot retrieve the version number from the routing data. This probably means you haven't included a '{0}' key in your route configuration.";
                throw new InvalidOperationException(String.Format(msg, this.RouteKey));
            }

            if (controllerVersion == null) {
                return null;
            }

            // convert instead of casting - allows all default values
            string rawVersionNumber = Convert.ToString(controllerVersion, CultureInfo.InvariantCulture);
            return rawVersionNumber;
        }
        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration = null, IHttpController instance = null, IHttpRouteData routeData = null, HttpRequestMessage request = null)
        {
            HttpConfiguration config = configuration ?? new HttpConfiguration();
            IHttpRouteData route = routeData ?? new HttpRouteData(new HttpRoute());
            HttpRequestMessage req = request ?? new HttpRequestMessage();
            req.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            req.Properties[HttpPropertyKeys.HttpRouteDataKey] = route;

            HttpControllerContext context = new HttpControllerContext(config, route, req);
            if (instance != null)
            {
                context.Controller = instance;
            }

            return context;
        }
Esempio n. 22
0
        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration = null, IHttpController instance = null, IHttpRouteData routeData = null, HttpRequestMessage request = null)
        {
            HttpConfiguration config = configuration ?? new HttpConfiguration();
            IHttpRouteData route = routeData ?? new HttpRouteData(new HttpRoute());
            HttpRequestMessage req = request ?? new HttpRequestMessage();
            req.SetConfiguration(config);
            req.SetRouteData(route);

            HttpControllerContext context = new HttpControllerContext(config, route, req);
            if (instance != null)
            {
                context.Controller = instance;
            }
            context.ControllerDescriptor = CreateControllerDescriptor(config);

            return context;
        }
Esempio n. 23
0
            private ReflectedHttpActionDescriptor[] GetInitialCandidateList(HttpControllerContext controllerContext, bool ignoreVerbs = false)
            {
                HttpMethod     incomingMethod = controllerContext.Request.Method;
                IHttpRouteData routeData      = controllerContext.RouteData;

                IHttpRoute route = routeData.Route;

                ReflectedHttpActionDescriptor[] actions;
                if (route != null)
                {
                    // Attribute routing gives the action selector an explicit initial candidate list.
                    actions = routeData.GetDirectRouteActions();
                    if (actions != null)
                    {
                        if (!ignoreVerbs)
                        {
                            actions = FindActionsForVerbWorker(incomingMethod, actions);
                        }

                        return(actions);
                    }
                }

                string actionName;

                if (routeData.Values.TryGetValue(RouteKeys.ActionKey, out actionName))
                {
                    // We have an explicit {action} value, do traditional binding. Just lookup by actionName
                    ReflectedHttpActionDescriptor[] actionsFoundByName = _standardActionNameMapping[actionName].ToArray();

                    // Throws HttpResponseException with NotFound status because no action matches the Name
                    if (actionsFoundByName.Length == 0)
                    {
                        throw new HttpResponseException(controllerContext.Request.CreateErrorResponse(
                                                            HttpStatusCode.NotFound,
                                                            Error.Format(SRResources.ResourceNotFound, controllerContext.Request.RequestUri),
                                                            Error.Format(SRResources.ApiControllerActionSelector_ActionNameNotFound, _controllerDescriptor.ControllerName, actionName)));
                    }

                    if (ignoreVerbs)
                    {
                        actions = actionsFoundByName;
                    }
                    else
                    {
                        actions = FilterIncompatibleVerbs(incomingMethod, actionsFoundByName);
                    }
                }
                else
                {
                    if (ignoreVerbs)
                    {
                        actions = _standardActionDescriptors;
                    }
                    else
                    {
                        // No direct routing or {action} parameter, infer it from the verb.
                        actions = FindActionsForVerb(incomingMethod);
                    }
                }

                return(actions);
            }
 public string BuildInstancePattern(Uri uri, IHttpRouteData routeData)
 {
     return BuildPattern(routeData, false);
 }
        private static Guid GetAffiliateKey(IHttpRouteData routeData) {

            var affiliateKey = routeData.Values["key"].ToString();
            return Guid.ParseExact(affiliateKey, "D");
        }
Esempio n. 26
0
        public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            /* Api Versioning
             *
             * # -- [1]Using Accept Header -- #
             *
             * In order to request a specific version of the Api using the
             * Accept Header method, a version must be specified
             * in the accept header of the request, in the style of
             * "Accept: application/json; version={version number}"
             *
             * # -- [2]Using Request Header -- #
             *
             * In order to request a specific version of the Api using the
             * Header method, a header in the style of "X-CountingKs-Version: {version number}"
             * needs to be added to the request
             *
             * # -- [3]Using QueryString -- #
             *
             * In order to request a specific version of the Api using the
             * QueryString method, a value in the style of "v={version number}"
             * needs to be added to the query string
             *
             * # -- [4]Using Custom Media Type -- #
             *
             * In order to request a specificversion of the Api using the
             * Custom Media Type method, a custom media type (CustomMediaType class)
             * must be added to the accept header of the request, in the style of
             * "Accept: application/vnd.countingks.{controller name}.v{version number}+json"
             *
             */

            // Gets a dictionary of all the exposed controllers
            IDictionary <string, HttpControllerDescriptor> controllers = GetControllerMapping();

            IHttpRouteData routeData = request.GetRouteData();

            // The name of the controller that the request is targetting
            string controllerName = (string)routeData.Values["controller"];

            // When attribute routing is being used
            if (string.IsNullOrWhiteSpace(controllerName))
            {
                return(base.SelectController(request));
            }

            if (!controllers.TryGetValue(controllerName, out HttpControllerDescriptor descriptor))
            {
                return(null);
            }

            ApiVersion apiVersion;

            apiVersion = GetVersionFromAcceptHeaderVersion(request);

            if (apiVersion == null)
            {
                apiVersion = GetVersionFromHeader(request);
            }

            if (apiVersion == null)
            {
                apiVersion = GetVersionFromQueryString(request);
            }

            if (apiVersion == null)
            {
                apiVersion = GetVersionFromMediaType(request, controllerName);
            }

            if (apiVersion == null)
            {
                apiVersion = GetMostRecentVersion();
            }

            string versionName = string.Concat(controllerName, "V", apiVersion.Version); // example: MeasureV2

            // Check if the controller for the selected version exists
            if (controllers.TryGetValue(versionName, out HttpControllerDescriptor versionDescriptor))
            {
                return(versionDescriptor);
            }

            return(descriptor);
        }
Esempio n. 27
0
        private Task <HttpResponseMessage> SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            IHttpRouteData routeData = request.GetRouteData();

            Contract.Assert(routeData != null);

            HttpControllerDescriptor httpControllerDescriptor = ControllerSelector.SelectController(request);

            if (httpControllerDescriptor == null)
            {
                return(TaskHelpers.FromResult(request.CreateErrorResponse(
                                                  HttpStatusCode.NotFound,
                                                  Error.Format(SRResources.ResourceNotFound, request.RequestUri),
                                                  SRResources.NoControllerSelected)));
            }

            IHttpController httpController = httpControllerDescriptor.CreateController(request);

            if (httpController == null)
            {
                return(TaskHelpers.FromResult(request.CreateErrorResponse(
                                                  HttpStatusCode.NotFound,
                                                  Error.Format(SRResources.ResourceNotFound, request.RequestUri),
                                                  SRResources.NoControllerCreated)));
            }

            HttpConfiguration controllerConfiguration = httpControllerDescriptor.Configuration;

            // Set the controller configuration on the request properties
            HttpConfiguration requestConfig = request.GetConfiguration();

            if (requestConfig == null)
            {
                request.SetConfiguration(controllerConfiguration);
            }
            else
            {
                if (requestConfig != controllerConfiguration)
                {
                    request.SetConfiguration(controllerConfiguration);
                }
            }

            HttpRequestContext requestContext = request.GetRequestContext();

            if (requestContext == null)
            {
                requestContext = new HttpRequestContext
                {
                    Configuration   = controllerConfiguration,
                    RouteData       = routeData,
                    Url             = new UrlHelper(request),
                    VirtualPathRoot = controllerConfiguration != null ? controllerConfiguration.VirtualPathRoot : null
                };
            }

            // Create context
            HttpControllerContext controllerContext = new HttpControllerContext(requestContext, request,
                                                                                httpControllerDescriptor, httpController);

            return(httpController.ExecuteAsync(controllerContext, cancellationToken));
        }
Esempio n. 28
0
        public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            HttpControllerDescriptor controllerDescriptor = null;

            // get list of all controllers provided by the default selector
            IDictionary <string, HttpControllerDescriptor> controllers = GetControllerMapping();

            IHttpRouteData routeData = request.GetRouteData();

            if (routeData == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            //check if this route is actually an attribute route
            IEnumerable <IHttpRouteData> attributeSubRoutes = routeData.GetSubRoutes();

            var apiVersion = GetVersionFromMediaType(request);

            if (attributeSubRoutes == null)
            {
                string controllerName = GetRouteVariable <string>(routeData, "controller");
                if (controllerName == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }

                string newControllerName = String.Concat(controllerName, "V", apiVersion);

                if (controllers.TryGetValue(newControllerName, out controllerDescriptor))
                {
                    return(controllerDescriptor);
                }
                else
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
            }
            else
            {
                // we want to find all controller descriptors whose controller type names end with
                // the following suffix (example: PeopleV1)
                string newControllerNameSuffix = String.Concat("V", apiVersion);

                IEnumerable <IHttpRouteData> filteredSubRoutes = attributeSubRoutes
                                                                 .Where(attrRouteData =>
                {
                    HttpControllerDescriptor currentDescriptor = GetControllerDescriptor(attrRouteData);

                    bool match = currentDescriptor.ControllerName.EndsWith(newControllerNameSuffix);

                    if (match && (controllerDescriptor == null))
                    {
                        controllerDescriptor = currentDescriptor;
                    }

                    return(match);
                });

                routeData.Values["MS_SubRoutes"] = filteredSubRoutes.ToArray();
            }

            return(controllerDescriptor);
        }
Esempio n. 29
0
        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration, IHttpRouteData routeData, HttpRequestMessage request)
        {
            HttpConfiguration  config = configuration ?? new HttpConfiguration();
            IHttpRouteData     route  = routeData ?? new HttpRouteData(new HttpRoute());
            HttpRequestMessage req    = request ?? new HttpRequestMessage();

            req.SetConfiguration(config);
            req.SetRouteData(route);
            return(new HttpControllerContext(config, route, req)
            {
                ControllerDescriptor = new HttpControllerDescriptor(config)
            });
        }
Esempio n. 30
0
        // this resolves the special folders such as SystemDrive or LocalSiteRoot
        public static bool TryParse(IHttpRouteData routeData, out string result)
        {
            result = null;

            string path = routeData != null ? routeData.Values["path"] as string : null;
            if (!String.IsNullOrEmpty(path))
            {
                if (String.Equals(path, SystemDriveFolder, StringComparison.OrdinalIgnoreCase) ||
                    path.IndexOf(SystemDriveFolder + VfsControllerBase.UriSegmentSeparator, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (!String.IsNullOrEmpty(SystemDrivePath))
                    {
                        string relativePath = path.Substring(SystemDriveFolder.Length);
                        if (String.IsNullOrEmpty(relativePath))
                        {
                            result = SystemDrivePath;
                        }
                        else
                        {
                            result = Path.GetFullPath(SystemDrivePath + relativePath);
                        }
                    }
                }
                else if (String.Equals(path, LocalSiteRootFolder, StringComparison.OrdinalIgnoreCase) ||
                    path.IndexOf(LocalSiteRootFolder + VfsControllerBase.UriSegmentSeparator, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (!String.IsNullOrEmpty(LocalSiteRootPath))
                    {
                        string relativePath = path.Substring(LocalSiteRootFolder.Length);
                        if (String.IsNullOrEmpty(relativePath))
                        {
                            result = LocalSiteRootPath;
                        }
                        else
                        {
                            result = Path.GetFullPath(LocalSiteRootPath + relativePath);
                        }
                    }
                }
            }
            
            return result != null;
        }
        // Get a value from the route data, if present.
        static T GetRouteVariable <T>(IHttpRouteData routeData, string name)
        {
            object result;

            return(routeData.Values.TryGetValue(name, out result) ? (T)result : default(T));
        }
 public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration, IHttpRouteData routeData)
 {
     return CreateControllerContext(configuration, routeData, null);
 }
Esempio n. 33
0
        public virtual HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            IHttpRouteData           routeData = request.GetRouteData();
            HttpControllerDescriptor controllerDescriptor;

            if (routeData != null)
            {
                controllerDescriptor = GetDirectRouteController(routeData);
                if (controllerDescriptor != null)
                {
                    return(controllerDescriptor);
                }
            }

            string controllerName = GetControllerName(request);

            if (String.IsNullOrEmpty(controllerName))
            {
                throw new HttpResponseException(
                          request.CreateErrorResponse(
                              HttpStatusCode.NotFound,
                              Error.Format(SRResources.ResourceNotFound, request.RequestUri),
                              Error.Format(SRResources.ControllerNameNotFound, request.RequestUri)
                              )
                          );
            }

            if (_controllerInfoCache.Value.TryGetValue(controllerName, out controllerDescriptor))
            {
                return(controllerDescriptor);
            }

            ICollection <Type> matchingTypes = _controllerTypeCache.GetControllerTypes(
                controllerName
                );

            // ControllerInfoCache is already initialized.
            Contract.Assert(matchingTypes.Count != 1);

            if (matchingTypes.Count == 0)
            {
                // no matching types
                throw new HttpResponseException(
                          request.CreateErrorResponse(
                              HttpStatusCode.NotFound,
                              Error.Format(SRResources.ResourceNotFound, request.RequestUri),
                              Error.Format(
                                  SRResources.DefaultControllerFactory_ControllerNameNotFound,
                                  controllerName
                                  )
                              )
                          );
            }
            else
            {
                // multiple matching types
                throw CreateAmbiguousControllerException(
                          request.GetRouteData().Route,
                          controllerName,
                          matchingTypes
                          );
            }
        }
 public ODataKeysValueProvider(IHttpRouteData routedata)
 {
     _routeData = routedata;
 }
Esempio n. 35
0
        private static IList <RouteValue> ProcessActionParam(HttpParameterDescriptor param, IHttpRouteData routeDataValues)
        {
            var propertyReader = new PropertyReader();

            if (propertyReader.IsSimpleType(param.ParameterType))
            {
                return(ProcessSimpleActionParam(param, routeDataValues));
            }

            return(ProcessCompoundActionParam(param, routeDataValues, propertyReader));
        }
Esempio n. 36
0
        private Task <HttpResponseMessage> SendAsyncCore(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw Error.ArgumentNull("request");
            }

            IHttpRouteData routeData = request.GetRouteData();

            Contract.Assert(routeData != null);

            HttpControllerDescriptor httpControllerDescriptor = ControllerSelector.SelectController(request);

            if (httpControllerDescriptor == null)
            {
                return(TaskHelpers.FromResult(request.CreateErrorResponse(
                                                  HttpStatusCode.NotFound,
                                                  Error.Format(SRResources.ResourceNotFound, request.RequestUri),
                                                  SRResources.NoControllerSelected)));
            }

            IHttpController httpController = httpControllerDescriptor.CreateController(request);

            if (httpController == null)
            {
                return(TaskHelpers.FromResult(request.CreateErrorResponse(
                                                  HttpStatusCode.NotFound,
                                                  Error.Format(SRResources.ResourceNotFound, request.RequestUri),
                                                  SRResources.NoControllerCreated)));
            }

            HttpConfiguration controllerConfiguration = httpControllerDescriptor.Configuration;

            // Set the controller configuration on the request properties
            HttpConfiguration requestConfig = request.GetConfiguration();

            if (requestConfig == null)
            {
                request.SetConfiguration(controllerConfiguration);
            }
            else
            {
                if (requestConfig != controllerConfiguration)
                {
                    request.SetConfiguration(controllerConfiguration);
                }
            }

            HttpRequestContext requestContext = request.GetRequestContext();

            // if the host doesn't create the context we will fallback to creating it.
            if (requestContext == null)
            {
                requestContext = new RequestBackedHttpRequestContext(request)
                {
                    // we are caching controller configuration to support per controller configuration.
                    Configuration = controllerConfiguration,
                };

                // if the host did not set a request context we will also set it back to the request.
                request.SetRequestContext(requestContext);
            }

            // Create context
            HttpControllerContext controllerContext = new HttpControllerContext(requestContext, request,
                                                                                httpControllerDescriptor, httpController);

            return(httpController.ExecuteAsync(controllerContext, cancellationToken));
        }
        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration = null, IHttpController instance = null, IHttpRouteData routeData = null, HttpRequestMessage request = null)
        {
            HttpConfiguration  config = configuration ?? new HttpConfiguration();
            IHttpRouteData     route  = routeData ?? new HttpRouteData(new HttpRoute());
            HttpRequestMessage req    = request ?? new HttpRequestMessage();

            req.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            req.Properties[HttpPropertyKeys.HttpRouteDataKey]     = route;

            HttpControllerContext context = new HttpControllerContext(config, route, req);

            if (instance != null)
            {
                context.Controller = instance;
            }

            return(context);
        }
Esempio n. 38
0
 public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration, IHttpRouteData routeData)
 {
     return(CreateControllerContext(configuration, routeData, null));
 }
Esempio n. 39
0
 private HttpControllerDescriptor GetControllerDescriptor(IHttpRouteData routeData)
 {
     return(((HttpActionDescriptor[])routeData.Route.DataTokens["actions"]).First().ControllerDescriptor);
 }
Esempio n. 40
0
 public static HttpControllerContext CreateControllerContext(IHttpRouteData routeData, HttpRequestMessage request)
 {
     return(CreateControllerContext(null, routeData, request));
 }
Esempio n. 41
0
 private string SerializeRouteData(IHttpRouteData routeData)
 {
     return(JsonConvert.SerializeObject(routeData));
 }
Esempio n. 42
0
        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration, IHttpRouteData routeData, HttpRequestMessage request)
        {
            HttpConfiguration  config = configuration ?? new HttpConfiguration();
            IHttpRouteData     route  = routeData ?? new HttpRouteData(new HttpRoute());
            HttpRequestMessage req    = request ?? new HttpRequestMessage();

            req.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;
            req.Properties[HttpPropertyKeys.HttpRouteDataKey]     = route;
            return(new HttpControllerContext(config, route, req)
            {
                ControllerDescriptor = new HttpControllerDescriptor(config)
            });
        }
Esempio n. 43
0
 /// <summary>
 ///     Returns a <see cref="HttpRouteDataAssertions" /> object that can be used to assert the current
 ///     <see cref="IHttpRouteData" />.
 /// </summary>
 public static HttpRouteDataAssertions Should(this IHttpRouteData actualValue)
 {
     return(new HttpRouteDataAssertions(actualValue));
 }
 public ODataKeysValueProvider(IHttpRouteData routedata)
 {
     _routeData = routedata;
 }
Esempio n. 45
0
        public virtual ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            CorsRequestContext   corsRequestContext = request.GetCorsRequestContext();
            HttpActionDescriptor actionDescriptor   = null;

            if (corsRequestContext.IsPreflight)
            {
                HttpRequestMessage targetRequest = new HttpRequestMessage(
                    new HttpMethod(corsRequestContext.AccessControlRequestMethod),
                    request.RequestUri
                    );

                request.RegisterForDispose(targetRequest);

                try
                {
                    foreach (var property in request.Properties)
                    {
                        // The RouteData and HttpContext from the preflight request properties contain information
                        // relevant to the preflight request and not the actual request, therefore we need to exclude them.
                        if (
                            property.Key != HttpPropertyKeys.HttpRouteDataKey &&
                            property.Key != HttpContextBaseKey
                            )
                        {
                            targetRequest.Properties.Add(property.Key, property.Value);
                        }
                    }

                    HttpConfiguration config = request.GetConfiguration();
                    if (config == null)
                    {
                        throw new InvalidOperationException(SRResources.NoConfiguration);
                    }

                    IHttpRouteData routeData = config.Routes.GetRouteData(request);
                    if (routeData == null)
                    {
                        // No route data found for selecting action with EnableCorsAttribute, thus no ICorsPolicyProvider is returned
                        // and let the CorsMessageHandler flow the request to the normal Web API pipeline.
                        return(null);
                    }

                    actionDescriptor = SelectAction(targetRequest, routeData, config);
                }
                catch
                {
                    if (DefaultPolicyProvider != null)
                    {
                        return(DefaultPolicyProvider);
                    }
                    throw;
                }
            }
            else
            {
                actionDescriptor = request.GetActionDescriptor();
            }

            return(GetCorsPolicyProvider(actionDescriptor));
        }
Esempio n. 46
0
        /// <inheritdoc/>
        public override string SelectAction(ODataPath odataPath, HttpControllerContext controllerContext, ILookup <string, HttpActionDescriptor> actionMap)
        {
            if (odataPath == null)
            {
                throw Error.ArgumentNull("odataPath");
            }

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

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

            HttpMethod     requestMethod = controllerContext.Request.Method;
            IHttpRouteData routeData     = controllerContext.RouteData;

            if (!IsSupportedRequestMethod(requestMethod))
            {
                return(null);
            }

            if (odataPath.PathTemplate == "~/entityset/key/navigation/$ref" ||
                odataPath.PathTemplate == "~/entityset/key/cast/navigation/$ref" ||
                odataPath.PathTemplate == "~/singleton/navigation/$ref" ||
                odataPath.PathTemplate == "~/singleton/cast/navigation/$ref")
            {
                NavigationPropertyLinkSegment navigationLinkSegment = (NavigationPropertyLinkSegment)odataPath.Segments.Last();
                IEdmNavigationProperty        navigationProperty    = navigationLinkSegment.NavigationProperty;
                IEdmEntityType declaringType = navigationProperty.DeclaringEntityType();

                string refActionName = FindRefActionName(actionMap, navigationProperty, declaringType, requestMethod);
                if (refActionName != null)
                {
                    if (odataPath.PathTemplate.StartsWith("~/entityset/key", StringComparison.Ordinal))
                    {
                        controllerContext.AddKeyValueToRouteData((KeySegment)odataPath.Segments[1]);
                    }

                    routeData.Values[ODataRouteConstants.NavigationProperty] = navigationLinkSegment.NavigationProperty.Name;
                    return(refActionName);
                }
            }
            else if ((requestMethod == HttpMethod.Delete) && (
                         odataPath.PathTemplate == "~/entityset/key/navigation/key/$ref" ||
                         odataPath.PathTemplate == "~/entityset/key/cast/navigation/key/$ref" ||
                         odataPath.PathTemplate == "~/singleton/navigation/key/$ref" ||
                         odataPath.PathTemplate == "~/singleton/cast/navigation/key/$ref"))
            {
                // the second key segment is the last segment in the path.
                // So the previous of last segment is the navigation property link segment.
                NavigationPropertyLinkSegment navigationLinkSegment = (NavigationPropertyLinkSegment)odataPath.Segments[odataPath.Segments.Count - 2];
                IEdmNavigationProperty        navigationProperty    = navigationLinkSegment.NavigationProperty;
                IEdmEntityType declaringType = navigationProperty.DeclaringEntityType();

                string refActionName = FindRefActionName(actionMap, navigationProperty, declaringType, requestMethod);
                if (refActionName != null)
                {
                    if (odataPath.PathTemplate.StartsWith("~/entityset/key", StringComparison.Ordinal))
                    {
                        controllerContext.AddKeyValueToRouteData((KeySegment)odataPath.Segments[1]);
                    }

                    routeData.Values[ODataRouteConstants.NavigationProperty] = navigationLinkSegment.NavigationProperty.Name;
                    controllerContext.AddKeyValueToRouteData((KeySegment)odataPath.Segments.Last(e => e is KeySegment), ODataRouteConstants.RelatedKey);
                    return(refActionName);
                }
            }

            return(null);
        }
Esempio n. 47
0
 private bool GetIsApiRoute(IHttpRouteData routeData)
 {
     return(routeData.Route.RouteTemplate.Contains("api/"));
 }
Esempio n. 48
0
        public static HttpControllerContext CreateControllerContext(HttpConfiguration configuration = null, IHttpController instance = null, IHttpRouteData routeData = null, HttpRequestMessage request = null)
        {
            HttpConfiguration  config = configuration ?? new HttpConfiguration();
            IHttpRouteData     route  = routeData ?? new HttpRouteData(new HttpRoute());
            HttpRequestMessage req    = request ?? new HttpRequestMessage();

            req.SetConfiguration(config);
            req.SetRouteData(route);

            HttpControllerContext context = new HttpControllerContext(config, route, req);

            if (instance != null)
            {
                context.Controller = instance;
            }
            context.ControllerDescriptor = CreateControllerDescriptor(config);

            return(context);
        }
Esempio n. 49
0
 private static string GetRequestedActionName(IHttpRouteData routeData)
 {
     return(GetRouteVariable <string>(routeData, ActionKey));
 }
Esempio n. 50
0
        public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
        {
            if (controllerContext == null)
            {
                throw new ArgumentNullException("controllerContext");
            }

            HttpRequestMessage request   = controllerContext.Request;
            ODataPath          odataPath = request.ODataProperties().Path;
            IEnumerable <IODataRoutingConvention> routingConventions = request.ODataProperties().RoutingConventions;
            IHttpRouteData routeData = controllerContext.RouteData;

            if (odataPath == null || routingConventions == null || routeData.Values.ContainsKey(ODataRouteConstants.Action))
            {
                return(_innerSelector.SelectAction(controllerContext));
            }

            ILookup <string, HttpActionDescriptor> actionMap = GetActionMapping(controllerContext.ControllerDescriptor);

            foreach (IODataRoutingConvention routingConvention in routingConventions)
            {
                string actionName = routingConvention.SelectAction(odataPath, controllerContext, actionMap);
                if (actionName != null)
                {
                    routeData.Values[ODataRouteConstants.Action] = actionName;
                    IEnumerable <HttpActionDescriptor> candidateActions = actionMap[actionName];
                    int countMatchingActions = candidateActions.Count();
                    if (countMatchingActions == 1)
                    {
                        HttpActionDescriptor selectedCandidate = candidateActions.First();
                        return(selectedCandidate);
                    }
                    else if (countMatchingActions == 0)
                    {
                        return(null);
                    }

                    if (candidateActions.Any(candidateAction => ChangeSetEntityModelBinder.ActionHasChangeSetEntityParameter(candidateAction)))
                    {
                        IEnumerable <HttpActionDescriptor> orderedActions = candidateActions.OrderBy(DetermineActionOrder);
                        // TODO: IDEAL: Select the first action with all parameters present
                        // Since I can't figure out a good way to determine that, this implementation returns
                        // the changeSetEntity action iff the request URI has a ContentId reference;
                        // otherwise it returns the next available action.
                        foreach (var candidateAction in orderedActions)
                        {
                            if (ChangeSetEntityModelBinder.ActionHasChangeSetEntityParameter(candidateAction))
                            {
                                if (ContentIdHelper.RequestHasContentIdReference(controllerContext.Request))
                                {
                                    return(candidateAction);
                                }
                                // else continue;
                            }
                            else
                            {
                                return(candidateAction);
                            }
                        }
                    }
                    else
                    {
                        // If there aren't any ChangeSet entity parameters in any of the candidate actions, just use the regular
                        // HttpActionSelector's implementation. It does a good job selecting the best match based on parameters, but it doesn't support
                        // using an expanded set of actions.
                        return(_innerSelector.SelectAction(controllerContext));
                    }
                }
            }

            throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.NotFound,
                                                                        string.Format("No matching resource found for {0}", controllerContext.Request.RequestUri)));
        }
Esempio n. 51
0
        private static IList <RouteValue> ProcessSimpleActionParam(HttpParameterDescriptor param, IHttpRouteData routeDataValues)
        {
            var routeValues = new List <RouteValue>();

            var paramName = param.ParameterName;
            var value     = ReadParamWithRouteValue(paramName, routeDataValues.Values);

            if (value != null)
            {
                routeValues.Add(value);
            }
            return(routeValues);
        }
Esempio n. 52
0
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return(Task.Run(() =>
            {
                IHttpRouteData routeData = request.GetRouteData();
                Contract.Assert(routeData != null);
                if (!routeData.Values.TryGetValue(RouteConstants.SysWFPath, out object obj))
                {
                    return request.CreateErrorResponse(HttpStatusCode.BadRequest, "workflow Id not set in request");
                }
                string id = obj.ToString();
                var invoker = GetWorkflowInvoker(id);
                if (invoker == null)
                {
                    return request.CreateErrorResponse(HttpStatusCode.BadRequest, "workflow Id not set in request");
                }
                var content = request.Content;
                string jsonContent = content.ReadAsStringAsync().Result;
                dynamic b = WFJson.Parse(jsonContent);
                var rtv = invoker.Invoke(new Dictionary <string, object>()
                {
                    { "context", _Setting.GetContext(request) },
                    { "data", b }
                });
                return request.CreateResponse(HttpStatusCode.OK, (rtv["output"] as WFJson)._JToken);
            }));

            WorkflowInvoker CreateWorkflowInvoker(string id)
            {
                WorkflowInvoker invoker  = null;
                Activity        activity = null;

                if (_Setting.GetStream != null)
                {
                    activity = ActivityFactory.Create(id, _Setting.GetStream);
                }
                else if (_Setting.GetFile != null)
                {
                    activity = ActivityFactory.Create(id, _Setting.GetFile);
                }
                if (activity == null)
                {
                    return(null);
                }
                invoker = new WorkflowInvoker(activity);
                return(invoker);
            }

            WorkflowInvoker GetWorkflowInvoker(string id)
            {
                if (_Setting.SafeMode)
                {
                    return(CreateWorkflowInvoker(id));
                }
                if (_InvokerCache.TryGetValue(id, out WorkflowInvoker invoker))
                {
                    return(invoker);
                }
                lock (_LockObj)
                {
                    if (!_InvokerCache.TryGetValue(id, out invoker))
                    {
                        invoker = CreateWorkflowInvoker(id);
                        _InvokerCache.TryAdd(id, invoker);
                    }
                }
                return(invoker);
            }
        }
Esempio n. 53
0
 public ApiRouteTester(HttpConfiguration conf, HttpRequestMessage req)
 {
     _config = conf;
     _request = req;
     _routeData = _config.Routes.GetRouteData(_request);
     _request.Properties[HttpPropertyKeys.HttpRouteDataKey] = _routeData;
     _controllerSelector = new DefaultHttpControllerSelector(_config);
     _controllerContext = new HttpControllerContext(_config, _routeData, _request);
 }
Esempio n. 54
0
        private static IList <RouteValue> ProcessCompoundActionParam(HttpParameterDescriptor param, IHttpRouteData routeDataValues, PropertyReader propertyReader)
        {
            var routeValues = new List <RouteValue>();

            var fieldNames = propertyReader.SimplePropertyNames(param.ParameterType);

            foreach (var fieldName in fieldNames)
            {
                var value = ReadParamWithRouteValue(fieldName.ToLowerInvariant(), routeDataValues.Values);
                if (value != null)
                {
                    routeValues.Add(value);
                }
            }

            return(routeValues);
        }
 public static HttpControllerContext CreateControllerContext(IHttpRouteData routeData, HttpRequestMessage request)
 {
     return CreateControllerContext(null, routeData, request);
 }
Esempio n. 56
0
 public static string AppPathOrNull(IHttpRouteData route) => route.Values[AppPathKey]?.ToString();
Esempio n. 57
0
        private void GenerateRouteData()
        {
            matchedRoute = config.Routes.GetRouteData(request);

            if (matchedRoute != null)
            {
                request.Properties[HttpPropertyKeys.HttpRouteDataKey] = matchedRoute;
                controllerSelector = (IHttpControllerSelector) Activator.CreateInstance(ApiRouteAssert.ControllerSelectorType, config);
                controllerContext = new HttpControllerContext(config, matchedRoute, request);
            }
        }
Esempio n. 58
0
 private string SerializeRouteData(IHttpRouteData routeData)
 {
     return(JsonConvert.SerializeObject(routeData, Formatting.Indented));
 }
        internal static void AddRouteDataToRequest(IHttpRouteData routeData, HttpRequestMessage request)
        {
            if (routeData.Values != null)
            {
                Dictionary<string, object> routeDataValues = new Dictionary<string, object>();
                foreach (var pair in routeData.Values)
                {
                    // translate any unspecified optional parameters to null values
                    // unspecified values still need to be included as part of binding data
                    // for correct binding to occur
                    var value = pair.Value != RouteParameter.Optional ? pair.Value : null;
                    routeDataValues.Add(pair.Key, value);
                }

                request.Properties.Add(ScriptConstants.AzureFunctionsHttpRouteDataKey, routeDataValues);
            }
        }
 internal CandidateActionWithParams(CandidateAction candidateAction, ISet <string> parameters, IHttpRouteData routeDataSource)
 {
     CandidateAction        = candidateAction;
     CombinedParameterNames = parameters;
     RouteDataSource        = routeDataSource;
 }