Exemplo n.º 1
0
        public VirtualPathData GetVirtualPath(VirtualPathContext context)
        {
            if (IsValidRequest(context.Context))
            {
                return _target.GetVirtualPath(context);
            }

            return null;
        }
Exemplo n.º 2
0
        public VirtualPathData GetVirtualPath(VirtualPathContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // We return null here because we're not responsible for generating the url, the route is.
            return null;
        }
Exemplo n.º 3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
            ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(minLevel: LogLevel.Verbose);
            app.UseIISPlatformHandler();

            var routeBuilder = new RouteBuilder();
            routeBuilder.ServiceProvider = app.ApplicationServices;

            routeBuilder.Routes.Add(new TemplateRoute(
                new HelloRouter(),
                "hello/{name:alpha}",
                app.ApplicationServices.GetService<IInlineConstraintResolver>()));

            var endpoint1 = new DelegateRouter(async (context) =>
                            await context
                                .HttpContext
                                .Response
                                .WriteAsync("Hello world! Route Values: " +
                                    string.Join("", context.RouteData.Values)));

            routeBuilder.DefaultHandler = endpoint1;

            routeBuilder.MapRoute(
                "Track Package Route",
                "package/{operation:regex(track|create|detonate)}/{id:int}");

            app.UseRouter(routeBuilder.Build());

            // demonstrate link generation
            var trackingRouteCollection = new RouteCollection();
            trackingRouteCollection.Add(routeBuilder.Routes[1]); // "Track Package Route"

            app.Run(async (context) =>
            {
                var dictionary = new RouteValueDictionary
                {
                    {"operation","create" },
                    {"id",123}
                };

                var vpc = new VirtualPathContext(context,
                    null, dictionary, "Track Package Route");

                context.Response.ContentType = "text/html";
                await context.Response.WriteAsync("Menu<hr/>");
                await context.Response.WriteAsync(@"<a href='" +
                    trackingRouteCollection.GetVirtualPath(vpc).VirtualPath +
                    "'>Create Package 123</a><br/>");
            });
        }
Exemplo n.º 4
0
        public VirtualPathData GetVirtualPath(VirtualPathContext context)
        {
            if (IsValidRequest(context.Context))
            {
                foreach (var route in _routes)
                {
                    var result = route.GetVirtualPath(context);
                    if(result != null)
                    {
                        return result;
                    }
                }
            }

            return null;
        }
Exemplo n.º 5
0
        public VirtualPathData GetVirtualPath(VirtualPathContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            EnsureServices(context.Context);

            // The contract of this method is to check that the values coming in from the route are valid;
            // that they match an existing action, setting IsBound = true if the values are OK.
            context.IsBound = _actionSelector.HasValidAction(context);

            // We return null here because we're not responsible for generating the url, the route is.
            return null;
        }
Exemplo n.º 6
0
        private static HtmlString createPostBackLink(IHtmlHelper helper,
                                              string text,
                                              string actionName,
                                              string controller)
        {
            var vpc = new VirtualPathContext(
                helper.ViewContext.HttpContext,
                null,
                (new RouteValueDictionary {
                      { "controller", controller },
                      { "action", actionName } })

                      );
            var actionUrl = helper.ViewContext.RouteData.Routers[0].GetVirtualPath(vpc);

            return new HtmlString(String.Format(@"<a href=""#"" class=""btn btn-default"" onclick=""wizard.WizardSubmit('{0}')"">{1}</a>",
                  actionUrl, text));
        }
Exemplo n.º 7
0
        public virtual string GetVirtualPath(VirtualPathContext context)
        {
            if (!string.IsNullOrEmpty(context.RouteName))
            {
                INamedRouter matchedNamedRoute;
                _namedRoutes.TryGetValue(context.RouteName, out matchedNamedRoute);

                var virtualPath = matchedNamedRoute != null?matchedNamedRoute.GetVirtualPath(context) : null;

                foreach (var unnamedRoute in _unnamedRoutes)
                {
                    var tempVirtualPath = unnamedRoute.GetVirtualPath(context);
                    if (tempVirtualPath != null)
                    {
                        if (virtualPath != null)
                        {
                            // There was already a previous route which matched the name.
                            throw new InvalidOperationException(
                                      Resources.FormatNamedRoutes_AmbiguousRoutesFound(context.RouteName));
                        }

                        virtualPath = tempVirtualPath;
                    }
                }

                return(virtualPath);
            }
            else
            {
                for (var i = 0; i < Count; i++)
                {
                    var route = this[i];

                    var path = route.GetVirtualPath(context);
                    if (path != null)
                    {
                        return(path);
                    }
                }
            }

            return(null);
        }
Exemplo n.º 8
0
 public bool HasValidAction(VirtualPathContext context)
 {
     return true;
 }
Exemplo n.º 9
0
 public VirtualPathData GetVirtualPath(VirtualPathContext context)
 {
     return null;
 }
Exemplo n.º 10
0
 /// <inheritdoc />
 public VirtualPathData GetVirtualPath(VirtualPathContext context)
 {
     var route = GetInnerRoute();
     return route.GetVirtualPath(context);
 }
Exemplo n.º 11
0
 public VirtualPathData GetVirtualPath(VirtualPathContext context)
 {
     return new VirtualPathData(this, "");
 }
Exemplo n.º 12
0
        /// <summary>
        /// Generates the absolute path of the url for the specified route values by
        /// using the specified route name.
        /// </summary>
        /// <param name="routeName">The name of the route that is used to generate the URL.</param>
        /// <param name="values">A dictionary that contains the parameters for a route.</param>
        /// <returns>The absolute path of the URL.</returns>
        protected virtual string GeneratePathFromRoute(string routeName, RouteValueDictionary values)
        {
            var context = new VirtualPathContext(HttpContext, AmbientValues, values, routeName);
            var pathData = Router.GetVirtualPath(context);
            if (pathData == null)
            {
                return null;
            }

            // VirtualPathData.VirtualPath returns string.Empty for null.
            Debug.Assert(pathData.VirtualPath != null);
            var pathBase = HttpContext.Request.PathBase;
            if (!pathBase.HasValue)
            {
                if (pathData.VirtualPath.Length == 0)
                {
                    return "/";
                }
                else if (!pathData.VirtualPath.StartsWith("/", StringComparison.Ordinal))
                {
                    return "/" + pathData.VirtualPath;
                }
                else
                {
                    return pathData.VirtualPath;
                }
            }
            else
            {
                if (pathData.VirtualPath.Length == 0)
                {
                    return pathBase;
                }
                else
                {
                    var builder = new StringBuilder(
                        pathBase.Value,
                        pathBase.Value.Length + pathData.VirtualPath.Length);

                    if (pathBase.Value.EndsWith("/", StringComparison.Ordinal))
                    {
                        builder.Length--;
                    }

                    if (!pathData.VirtualPath.StartsWith("/", StringComparison.Ordinal))
                    {
                        builder.Append("/");
                    }

                    builder.Append(pathData.VirtualPath);

                    return builder.ToString();
                }
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Generates the absolute path of the url for the specified route values by
        /// using the specified route name.
        /// </summary>
        /// <param name="routeName">The name of the route that is used to generate the URL.</param>
        /// <param name="values">A dictionary that contains the parameters for a route.</param>
        /// <returns>The absolute path of the URL.</returns>
        protected virtual string GeneratePathFromRoute(string routeName, IDictionary<string, object> values)
        {
            var context = new VirtualPathContext(_httpContext, _ambientValues, values, routeName);
            var pathData = _router.GetVirtualPath(context);
            if (pathData == null)
            {
                return null;
            }

            // VirtualPathData.VirtualPath returns string.Empty for null.
            Debug.Assert(pathData.VirtualPath != null);

            var fullPath = _httpContext.Request.PathBase.Add(pathData.VirtualPath).Value;
            if (fullPath.Length == 0)
            {
                return "/";
            }
            else
            {
                return fullPath;
            }
        }
Exemplo n.º 14
0
        // This method attempts to ensure that the route that's about to generate a link will generate a link
        // to an existing action. This method is called by a route (through MvcApplication) prior to generating
        // any link - this gives WebFX a chance to 'veto' the values provided by a route.
        //
        // This method does not take httpmethod or dynamic action constraints into account.
        public virtual bool HasValidAction(VirtualPathContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.ProvidedValues == null)
            {
                // We need the route's values to be able to double check our work.
                return false;
            }

            var tree = _decisionTreeProvider.DecisionTree;
            var matchingRouteConstraints = tree.Select(context.ProvidedValues);

            return matchingRouteConstraints.Count > 0;
        }
Exemplo n.º 15
0
        private VirtualPathData GenerateVirtualPath(VirtualPathContext context, AttributeRouteLinkGenerationEntry entry)
        {
            // In attribute the context includes the values that are used to select this entry - typically
            // these will be the standard 'action', 'controller' and maybe 'area' tokens. However, we don't
            // want to pass these to the link generation code, or else they will end up as query parameters.
            //
            // So, we need to exclude from here any values that are 'required link values', but aren't
            // parameters in the template.
            //
            // Ex:
            //      template: api/Products/{action}
            //      required values: { id = "5", action = "Buy", Controller = "CoolProducts" }
            //
            //      result: { id = "5", action = "Buy" }
            var inputValues = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
            foreach (var kvp in context.Values)
            {
                if (entry.RequiredLinkValues.ContainsKey(kvp.Key))
                {
                    var parameter = entry.Template.Parameters
                        .FirstOrDefault(p => string.Equals(p.Name, kvp.Key, StringComparison.OrdinalIgnoreCase));

                    if (parameter == null)
                    {
                        continue;
                    }
                }

                inputValues.Add(kvp.Key, kvp.Value);
            }

            var bindingResult = entry.Binder.GetValues(context.AmbientValues, inputValues);
            if (bindingResult == null)
            {
                // A required parameter in the template didn't get a value.
                return null;
            }

            var matched = RouteConstraintMatcher.Match(
                entry.Constraints,
                bindingResult.CombinedValues,
                context.Context,
                this,
                RouteDirection.UrlGeneration,
                _constraintLogger);

            if (!matched)
            {
                // A constraint rejected this link.
                return null;
            }

            // These values are used to signal to the next route what we would produce if we round-tripped
            // (generate a link and then parse). In MVC the 'next route' is typically the MvcRouteHandler.
            var providedValues = new Dictionary<string, object>(
                bindingResult.AcceptedValues,
                StringComparer.OrdinalIgnoreCase);
            providedValues.Add(AttributeRouting.RouteGroupKey, entry.RouteGroup);

            var childContext = new VirtualPathContext(context.Context, context.AmbientValues, context.Values)
            {
                ProvidedValues = providedValues,
            };

            var pathData = _next.GetVirtualPath(childContext);
            if (pathData != null)
            {
                // If path is non-null then the target router short-circuited, we don't expect this
                // in typical MVC scenarios.
                return pathData;
            }
            else if (!childContext.IsBound)
            {
                // The target router has rejected these values. We don't expect this in typical MVC scenarios.
                return null;
            }

            var path = entry.Binder.BindValues(bindingResult.AcceptedValues);
            if (path == null)
            {
                return null;
            }

            return new VirtualPathData(this, path);
        }
Exemplo n.º 16
0
        private VirtualPathData GetVirtualPath(VirtualPathContext context, List<IRouter> routes)
        {
            for (var i = 0; i < routes.Count; i++)
            {
                var route = routes[i];

                var pathData = route.GetVirtualPath(context);
                if (pathData != null)
                {
                    return pathData;
                }
            }

            return null;
        }
Exemplo n.º 17
0
        public virtual VirtualPathData GetVirtualPath(VirtualPathContext context)
        {
            EnsureOptions(context.HttpContext);

            if (!string.IsNullOrEmpty(context.RouteName))
            {
                VirtualPathData namedRoutePathData = null;
                INamedRouter matchedNamedRoute;
                if (_namedRoutes.TryGetValue(context.RouteName, out matchedNamedRoute))
                {
                    namedRoutePathData = matchedNamedRoute.GetVirtualPath(context);
                }

                var pathData = GetVirtualPath(context, _unnamedRoutes);

                // If the named route and one of the unnamed routes also matches, then we have an ambiguity.
                if (namedRoutePathData != null && pathData != null)
                {
                    var message = Resources.FormatNamedRoutes_AmbiguousRoutesFound(context.RouteName);
                    throw new InvalidOperationException(message);
                }

                return NormalizeVirtualPath(namedRoutePathData ?? pathData);
            }
            else
            {
                return NormalizeVirtualPath(GetVirtualPath(context, _routes));
            }
        }
Exemplo n.º 18
0
        private string GeneratePathFromRoute(string routeName, IDictionary<string, object> values)
        {
            var context = new VirtualPathContext(_httpContext, _ambientValues, values, routeName);
            var path = _router.GetVirtualPath(context);
            if (path == null)
            {
                return null;
            }

            // See Routing Issue#31
            if (path.Length > 0 && path[0] != '/')
            {
                path = "/" + path;
            }

            var fullPath = _httpContext.Request.PathBase.Add(new PathString(path)).Value;
            if (fullPath.Length == 0)
            {
                return "/";
            }
            else
            {
                return fullPath;
            }
        }
 public VirtualPathData GetVirtualPath(VirtualPathContext context) {
     foreach(var parameter in _matcher.Template.Parameters) {
         context.Values.Remove(parameter.Name);
     }
     return _innerRoute.GetVirtualPath(context);
 }
Exemplo n.º 20
0
 public VirtualPathData GetVirtualPath(VirtualPathContext context)
 {
     context.IsBound = true;
     return null;
 }
Exemplo n.º 21
0
 public string GetVirtualPath(VirtualPathContext context)
 {
     return("");
 }
Exemplo n.º 22
0
 /// <inheritdoc />
 public VirtualPathData GetVirtualPath(VirtualPathContext context)
 {
     var router = GetTreeRouter();
     return router.GetVirtualPath(context);
 }
Exemplo n.º 23
0
 private VirtualPathData GetVirtualPathForNamedRoute(VirtualPathContext context)
 {
     AttributeRouteLinkGenerationEntry entry;
     if (_namedEntries.TryGetValue(context.RouteName, out entry))
     {
         var path = GenerateVirtualPath(context, entry);
         if (path != null)
         {
             context.IsBound = true;
             return path;
         }
     }
     return null;
 }
Exemplo n.º 24
0
 public VirtualPathData GetVirtualPath(VirtualPathContext context)
 {
     return(new VirtualPathData(this, ""));
 }
Exemplo n.º 25
0
        private bool ContextHasSameValue(VirtualPathContext context, string key, object value)
        {
            object providedValue;
            if (!context.Values.TryGetValue(key, out providedValue))
            {
                // If the required value is an 'empty' route value, then ignore ambient values.
                // This handles a case where we're generating a link to an action like:
                // { area = "", controller = "Home", action = "Index" }
                //
                // and the ambient values has a value for area.
                if (value != null)
                {
                    context.AmbientValues.TryGetValue(key, out providedValue);
                }
            }

            return TemplateBinder.RoutePartsEqual(providedValue, value);
        }
Exemplo n.º 26
0
 public VirtualPathData GetVirtualPath(VirtualPathContext context)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 27
0
        public virtual VirtualPathData GetVirtualPath(VirtualPathContext context)
        {
            EnsureOptions(context.Context);

            // If we're using Best-Effort link generation then it means that we'll first look for a route where
            // the route values are validated (context.IsBound == true). If we can't find a match like that, then
            // we'll return the path from the first route to return one.
            var useBestEffort = _options.UseBestEffortLinkGeneration;

            if (!string.IsNullOrEmpty(context.RouteName))
            {
                var isValidated = false;
                VirtualPathData bestPathData = null;
                INamedRouter matchedNamedRoute;
                if (_namedRoutes.TryGetValue(context.RouteName, out matchedNamedRoute))
                {
                    bestPathData = matchedNamedRoute.GetVirtualPath(context);
                    isValidated = context.IsBound;
                }

                // If we get here and context.IsBound == true, then we know we have a match, we want to keep
                // iterating to see if we have multiple matches.
                foreach (var unnamedRoute in _unnamedRoutes)
                {
                    // reset because we're sharing the context
                    context.IsBound = false;

                    var pathData = unnamedRoute.GetVirtualPath(context);
                    if (pathData == null)
                    {
                        continue;
                    }

                    if (bestPathData != null)
                    {
                        // There was already a previous route which matched the name.
                        throw new InvalidOperationException(
                            Resources.FormatNamedRoutes_AmbiguousRoutesFound(context.RouteName));
                    }
                    else if (context.IsBound)
                    {
                        // This is the first 'validated' match that we've found.
                        bestPathData = pathData;
                        isValidated = true;
                    }
                    else
                    {
                        Debug.Assert(bestPathData == null);

                        // This is the first 'unvalidated' match that we've found.
                        bestPathData = pathData;
                        isValidated = false;
                    }
                }

                if (isValidated || useBestEffort)
                {
                    context.IsBound = isValidated;

                    if (bestPathData != null)
                    {
                        bestPathData = new VirtualPathData(
                            bestPathData.Router,
                            NormalizeVirtualPath(bestPathData.VirtualPath),
                            bestPathData.DataTokens);
                    }

                    return bestPathData;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                VirtualPathData bestPathData = null;
                for (var i = 0; i < Count; i++)
                {
                    var route = this[i];

                    var pathData = route.GetVirtualPath(context);
                    if (pathData == null)
                    {
                        continue;
                    }

                    if (context.IsBound)
                    {
                        // This route has validated route values, short circuit.
                        return new VirtualPathData(
                            pathData.Router,
                            NormalizeVirtualPath(pathData.VirtualPath),
                            pathData.DataTokens);
                    }
                    else if (bestPathData == null)
                    {
                        // The values aren't validated, but this is the best we've seen so far
                        bestPathData = pathData;
                    }
                }

                if (useBestEffort)
                {
                    return new VirtualPathData(
                        bestPathData.Router,
                        NormalizeVirtualPath(bestPathData.VirtualPath),
                        bestPathData.DataTokens);
                }
                else
                {
                    return null;
                }
            }
        }
Exemplo n.º 28
0
            public VirtualPathData GetVirtualPath(VirtualPathContext context)
            {
                GenerationContext = context;

                if (GenerationDelegate == null)
                {
                    context.IsBound = true;
                }
                else
                {
                    context.IsBound = GenerationDelegate(context);
                }

                return null;
            }
Exemplo n.º 29
0
 protected abstract VirtualPathData OnVirtualPathGenerated(VirtualPathContext context);
Exemplo n.º 30
0
        public virtual VirtualPathData GetVirtualPath(VirtualPathContext context)
        {
            EnsureOptions(context.Context);

            // If we're using Best-Effort link generation then it means that we'll first look for a route where
            // the route values are validated (context.IsBound == true). If we can't find a match like that, then
            // we'll return the path from the first route to return one.
            var useBestEffort = _options.UseBestEffortLinkGeneration;

            if (!string.IsNullOrEmpty(context.RouteName))
            {
                var             isValidated  = false;
                VirtualPathData bestPathData = null;
                INamedRouter    matchedNamedRoute;
                if (_namedRoutes.TryGetValue(context.RouteName, out matchedNamedRoute))
                {
                    bestPathData = matchedNamedRoute.GetVirtualPath(context);
                    isValidated  = context.IsBound;
                }

                // If we get here and context.IsBound == true, then we know we have a match, we want to keep
                // iterating to see if we have multiple matches.
                foreach (var unnamedRoute in _unnamedRoutes)
                {
                    // reset because we're sharing the context
                    context.IsBound = false;

                    var pathData = unnamedRoute.GetVirtualPath(context);
                    if (pathData == null)
                    {
                        continue;
                    }

                    if (bestPathData != null)
                    {
                        // There was already a previous route which matched the name.
                        throw new InvalidOperationException(
                                  Resources.FormatNamedRoutes_AmbiguousRoutesFound(context.RouteName));
                    }
                    else if (context.IsBound)
                    {
                        // This is the first 'validated' match that we've found.
                        bestPathData = pathData;
                        isValidated  = true;
                    }
                    else
                    {
                        Debug.Assert(bestPathData == null);

                        // This is the first 'unvalidated' match that we've found.
                        bestPathData = pathData;
                        isValidated  = false;
                    }
                }

                if (isValidated || useBestEffort)
                {
                    context.IsBound = isValidated;

                    if (bestPathData != null)
                    {
                        bestPathData = new VirtualPathData(
                            bestPathData.Router,
                            NormalizeVirtualPath(bestPathData.VirtualPath),
                            bestPathData.DataTokens);
                    }

                    return(bestPathData);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                VirtualPathData bestPathData = null;
                for (var i = 0; i < Count; i++)
                {
                    var route = this[i];

                    var pathData = route.GetVirtualPath(context);
                    if (pathData == null)
                    {
                        continue;
                    }

                    if (context.IsBound)
                    {
                        // This route has validated route values, short circuit.
                        return(new VirtualPathData(
                                   pathData.Router,
                                   NormalizeVirtualPath(pathData.VirtualPath),
                                   pathData.DataTokens));
                    }
                    else if (bestPathData == null)
                    {
                        // The values aren't validated, but this is the best we've seen so far
                        bestPathData = pathData;
                    }
                }

                if (useBestEffort)
                {
                    return(new VirtualPathData(
                               bestPathData.Router,
                               NormalizeVirtualPath(bestPathData.VirtualPath),
                               bestPathData.DataTokens));
                }
                else
                {
                    return(null);
                }
            }
        }
        private VirtualPathContext CreateContext(object values, object ambientValues = null)
        {
            var context = new VirtualPathContext(
                new DefaultHttpContext(),
                new RouteValueDictionary(ambientValues),
                new RouteValueDictionary(values));

            return context;
        }
Exemplo n.º 32
0
 public VirtualPathData GetVirtualPath(VirtualPathContext context)
 {
     return _defaultHandler.GetVirtualPath(context);
 }
Exemplo n.º 33
0
 public VirtualPathData GetVirtualPath(VirtualPathContext context)
 {
     // We don't really care what the values look like.
     context.IsBound = true;
     return null;
 }
Exemplo n.º 34
0
 public VirtualPathData GetVirtualPath(VirtualPathContext context)
 {
     // We just want to act as a pass-through for link generation
     return _next.GetVirtualPath(context);
 }