public static RouteValueDictionary GetPageRoute(this RequestContext requestContext, ContentReference contentLink) { var values = new RouteValueDictionary(); values[RoutingConstants.NodeKey] = contentLink; values[RoutingConstants.LanguageKey] = ContentLanguage.PreferredCulture.Name; return values; }
public string GetRouteDescriptorKey(HttpContextBase httpContext, RouteBase routeBase) { var route = routeBase as Route; var dataTokens = new RouteValueDictionary(); if (route != null) { dataTokens = route.DataTokens; } else { var routeData = routeBase.GetRouteData(httpContext); if (routeData != null) { dataTokens = routeData.DataTokens; } } var keyBuilder = new StringBuilder(); if (route != null) { keyBuilder.AppendFormat("url={0};", route.Url); } // the data tokens are used in case the same url is used by several features, like *{path} (Rewrite Rules and Home Page Provider) if (dataTokens != null) { foreach (var key in dataTokens.Keys) { keyBuilder.AppendFormat("{0}={1};", key, dataTokens[key]); } } return keyBuilder.ToString().ToLowerInvariant(); }
public ActionLink BuildLink(Theme theme) { RouteValueDictionary routeValueDictionary = new RouteValueDictionary(); routeValueDictionary.Add("id", theme.Id); ActionLink actionLink = new ActionLink("Play", "Training", routeValueDictionary); return actionLink; }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (routeDirection == RouteDirection.UrlGeneration) { return true; } object versionValue; if (!values.TryGetValue(parameterName, out versionValue)) { return true; } if (versionValue == null || versionValue == UrlParameter.Optional) { return true; } string versionText = versionValue.ToString(); if (versionText.Length == 0) { return true; } SemanticVersion ignored; return SemanticVersion.TryParse(versionText, out ignored); }
// To only allow *supported* cultures as the first part of the route, instead of anything in the format xx or xx-xx comment the lower method // and uncomment this one, and make CultureManager.CultureIsSupported public. //public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) //{ // if (!values.ContainsKey(parameterName)) // return false; // string potentialCultureName = (string)values[parameterName]; // return CultureManager.CultureIsSupported(potentialCultureName); //} public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (!values.ContainsKey(parameterName)) return false; string potentialCultureName = (string)values[parameterName]; return CultureFormatChecker.FormattedAsCulture(potentialCultureName); }
// TODO: Remove when https://github.com/aspnet/Mvc/issues/4846 is fixed public static IRouteBuilder MapAreaRoute(this IRouteBuilder routeBuilder, string name, string area, string template, string controller, string action) { if (routeBuilder == null) { throw new ArgumentNullException(nameof(routeBuilder)); } if (string.IsNullOrEmpty(area)) { throw new ArgumentException(nameof(area)); } var defaultsDictionary = new RouteValueDictionary(); defaultsDictionary["area"] = area; defaultsDictionary["controller"] = controller; defaultsDictionary["action"] = action; var constraintsDictionary = new RouteValueDictionary(); constraintsDictionary["area"] = new StringRouteConstraint(area); routeBuilder.MapRoute(name, template, defaultsDictionary, constraintsDictionary, null); return routeBuilder; }
public override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); var principal = HttpContext.Current.User as IClaimsPrincipal; var buffer = new StringBuilder(); if (principal != null && principal.Identity.IsAuthenticated) { foreach (var claim in Claims) { if (!principal.Identities[0].Claims.Any(c => c.ClaimType == claim)) { buffer.AppendLine(String.Format("Claim '{0}' not provided.", claim)); } } if (buffer.Length > 0) { var redirectTargetDictionary = new RouteValueDictionary { {"action", "Error"}, {"controller", "Home"}, {"message", buffer.ToString()} }; filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary); } } }
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { var internalRoute = MyRoute; if (internalRoute != null && !internalRoute.Url.Contains("{")) { return null; } var vpd = base.GetVirtualPath(requestContext, values); if (vpd != null) { var virtualPath = vpd.VirtualPath; if (RequireLowerCase) { virtualPath = virtualPath.ToLowerInvariant(); } if (AppendTrailingSlash) { var queryIndex = virtualPath.IndexOf('?'); string queryPart = string.Empty; if (queryIndex > -1) { queryPart = virtualPath.Substring(queryIndex); virtualPath = virtualPath.Substring(0, queryIndex); } if (!virtualPath.EndsWith("/")) { virtualPath = virtualPath + "/"; } virtualPath += queryPart; } vpd.VirtualPath = virtualPath; } return vpd; }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { Debug.WriteLine(httpContext.Request.HttpMethod == "GET"); return httpContext.Request.UserAgent != null && httpContext.Request.UserAgent.Contains(requiredUserAgent); }
/// <summary> /// Initializes a new instance of the <see cref="UIRoute"/> class. /// </summary> /// <param name="url">The URL.</param> /// <param name="defaults">The defaults.</param> /// <param name="routeHandler">The route handler.</param> public UIRoute(string url, RouteValueDictionary defaults, IRouteHandler routeHandler) : base(url, defaults, routeHandler) { _url = url; _defaults = defaults; _routeHandler = routeHandler; }
private static string GetOutput(object tokenReplacements) { // Read the contents of the html template. var assembly = Assembly.GetExecutingAssembly(); var fileName = "{0}.LogRoutes.html".FormatWith(typeof(LogRoutesHandler).Namespace); string fileContent; using (var stream = assembly.GetManifestResourceStream(fileName)) { if (stream == null) throw new AttributeRoutingException( "The file \"{0}\" cannot be found as an embedded resource.".FormatWith(fileName)); using (var reader = new StreamReader(stream)) fileContent = reader.ReadToEnd(); } // Replace tokens in the template with appropriate content var outputBuilder = new StringBuilder(fileContent); var tokenReplacementsDictionary = new RouteValueDictionary(tokenReplacements); foreach (var key in tokenReplacementsDictionary.Keys) outputBuilder.Replace("{{{0}}}".FormatWith(key), tokenReplacementsDictionary[key].ToString()); return outputBuilder.ToString(); }
/// <summary> /// Creates a new <see cref="VirtualPathContext"/>. /// </summary> /// <param name="httpContext">The <see cref="Http.HttpContext"/> associated with the current request.</param> /// <param name="ambientValues">The set of route values associated with the current request.</param> /// <param name="values">The set of new values provided for virtual path generation.</param> public VirtualPathContext( HttpContext httpContext, RouteValueDictionary ambientValues, RouteValueDictionary values) : this(httpContext, ambientValues, values, null) { }
public static string Generate(RequestContext requestContext, NavigationRequest navigationItem, RouteValueDictionary routeValues) { if (requestContext == null) throw new ArgumentNullException("requestContext"); if (navigationItem == null) throw new ArgumentNullException("navigationItem"); var urlHelper = new UrlHelper(requestContext); string generatedUrl = null; if (!string.IsNullOrEmpty(navigationItem.RouteName)) { generatedUrl = urlHelper.RouteUrl(navigationItem.RouteName, routeValues); } else if (!string.IsNullOrEmpty(navigationItem.ControllerName) && !string.IsNullOrEmpty(navigationItem.ActionName)) { generatedUrl = urlHelper.Action(navigationItem.ActionName, navigationItem.ControllerName, routeValues, null, null); } else if (!string.IsNullOrEmpty(navigationItem.Url)) { generatedUrl = navigationItem.Url.StartsWith("~/", StringComparison.Ordinal) ? urlHelper.Content(navigationItem.Url) : navigationItem.Url; } else if (routeValues.Any()) { generatedUrl = urlHelper.RouteUrl(routeValues); } return generatedUrl; }
public static string SubdomainAction(this UrlHelper urlHelper, string actionName, string controllerName, string areaName = "") { var routeValues = new RouteValueDictionary { { "area", areaName } }; string baseUrl = GetDomainBase(urlHelper, null, actionName, controllerName, routeValues); return BuildUri(baseUrl, urlHelper.Action(actionName, controllerName, routeValues)); }
public static void RegisterRoutes(RouteCollection routes) { var def = new RouteValueDictionary(new { user = "******" }); var reg = new RouteValueDictionary(new { user = "******" }); // Register a route for Page/{User} routes.MapPageRoute( "user-page", // Route name "w/{user}", // Route URL "~/Pv.aspx", // Web page to handle route true, def, reg ); // Register a route for Page/{User} routes.MapPageRoute( "user-card", // Route name "c/{user}", // Route URL "~/Cv.aspx", // Web page to handle route true, def, reg ); // Register a route for Page/{User} routes.MapPageRoute( "user-imgs", // Route name "p/{user}", // Route URL "~/Id.aspx", // Web page to handle route true, def, reg ); }
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { // Grab and cast the controller to allow for Alerts var controller = (BaseController) filterContext.Controller; // If the user is authenticated and seeing this, they must not have the proper roles if (filterContext.HttpContext.User.Identity.IsAuthenticated) { // Alert controller.Danger("You have attempted to access a portion of the website you do not have access to"); // Redirect filterContext.Result = controller.RedirectToAction("Index", "Home"); } // If the user is not authenticated all together, bring them to the login page else { // Build the Route values with the request URL for redirect var returnUrl = filterContext.HttpContext.Request.Url?.LocalPath; var routeValues = new RouteValueDictionary(new {returnUrl}); // Alert controller.Danger("You must Login to access this portion of the Website"); // Redirect filterContext.Result = controller.RedirectToAction("Login", "Account", routeValues); } }
public static RouteValueDictionary MergeRouteValues(string actionName, string controllerName, RouteValueDictionary implicitRouteValues, RouteValueDictionary routeValues, bool includeImplicitMvcValues) { var routeValueDictionary = new RouteValueDictionary(); if (includeImplicitMvcValues) { object obj; if (implicitRouteValues != null && implicitRouteValues.TryGetValue("action", out obj)) { routeValueDictionary["action"] = obj; } if (implicitRouteValues != null && implicitRouteValues.TryGetValue("controller", out obj)) { routeValueDictionary["controller"] = obj; } } if (routeValues != null) { foreach (var keyValuePair in GetRouteValues(routeValues)) { routeValueDictionary[keyValuePair.Key] = keyValuePair.Value; } } if (actionName != null) { routeValueDictionary["action"] = actionName; } if (controllerName != null) { routeValueDictionary["controller"] = controllerName; } return routeValueDictionary; }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (httpContext == null || !httpContext.Request.IsLocal ) return false; return true; }
public string GetUrl(string menuItemUrl, RouteValueDictionary routeValueDictionary) { var url = string.IsNullOrEmpty(menuItemUrl) && (routeValueDictionary == null || routeValueDictionary.Count == 0) ? "~/" : !string.IsNullOrEmpty(menuItemUrl) ? menuItemUrl : _urlHelper.RouteUrl(routeValueDictionary); var schemes = new[] { "http", "https", "tel", "mailto" }; if (!string.IsNullOrEmpty(url) && _urlHelper.RequestContext.HttpContext != null && !(url.StartsWith("/") || schemes.Any(scheme => url.StartsWith(scheme + ":")))) { if (!url.StartsWith("#")) { if (url.StartsWith("~/")) { if (!String.IsNullOrEmpty(_shellSettings.RequestUrlPrefix)) { url = _shellSettings.RequestUrlPrefix + "/" + url.Substring(2); } else { url = url.Substring(2); } } var appPath = _urlHelper.RequestContext.HttpContext.Request.ApplicationPath; if (appPath == "/") appPath = ""; url = string.Format("{0}/{1}", appPath, url); } } return url; }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) #endif { if (parameterName == null) { throw Error.ArgumentNull("parameterName"); } if (values == null) { throw Error.ArgumentNull("values"); } object value; if (values.TryGetValue(parameterName, out value) && value != null) { string valueString = Convert.ToString(value, CultureInfo.InvariantCulture); int length = valueString.Length; if (Length.HasValue) { return length == Length.Value; } else { return length >= MinLength.Value && length <= MaxLength.Value; } } return false; }
public static IDisposable Begin(string tagName, TextWriter writer, RouteValueDictionary htmlAttributes) { var tag = new TagBuilder(tagName); tag.MergeAttributes(htmlAttributes); return new TagWrapper(tag, writer); }
/// <summary> /// Gets a route for provider configuration /// </summary> /// <param name="actionName">Action name</param> /// <param name="controllerName">Controller name</param> /// <param name="routeValues">Route values</param> public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues) { // no configuration required actionName = null; controllerName = null; routeValues = null; }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { object value; if (values.TryGetValue(parameterName, out value)) { var parameterValue = Convert.ToString(value); var path = FindPath(parameterValue); if (path == null) { return false; } var archiveData = FindArchiveData(parameterValue); if (archiveData == null) { return false; } try { // is this a valid date ? archiveData.ToDateTime(); } catch { return false; } var autoroute = _pathResolutionService.GetPath(path); return autoroute != null && autoroute.Is<BlogPart>(); } return false; }
private SiteMapNode AddNodeRecursive(XmlNode xmlNode, SiteMapNode parent, RequestContext context) { var routeValues = (from XmlNode attrib in xmlNode.Attributes where !reservedNames.Contains(attrib.Name.ToLower()) select new { attrib.Name, attrib.Value }).ToDictionary(x => x.Name, x => (object)x.Value); RouteValueDictionary routeDict = new RouteValueDictionary(routeValues); VirtualPathData virtualPathData = RouteTable.Routes.GetVirtualPath(context, routeDict); if (virtualPathData == null) { string message = "RoutingSiteMapProvider is unable to locate Route for " + "Controller: '" + routeDict["controller"] + "', Action: '" + routeDict["action"] + "'. " + "Make sure a route has been defined for this SiteMap Node."; throw new InvalidOperationException(message); } string url = virtualPathData.VirtualPath; string title = xmlNode.Attributes["title"].Value; SiteMapNode node = new SiteMapNode(this, Guid.NewGuid().ToString(), url, title); base.AddNode(node, parent); foreach (XmlNode childNode in xmlNode.ChildNodes) { AddNodeRecursive(childNode, node, context); } return node; }
/// <summary> /// /// </summary> /// <param name="httpContext"></param> /// <param name="route"></param> /// <param name="parameterName"></param> /// <param name="values"></param> /// <param name="routeDirection"></param> /// <returns></returns> public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { if (values[parameterName].ToString().ToLower() == "rqitems") return true; else return false; }
public void RegisterRoutes(RouteCollection routes) { //Register 1 route var basePath = Config.GetBasePath(); var constrasints = new RouteValueDictionary {{"method", new ApiHttpMethodConstraint("OPTIONS")}}; routes.Add(new Route(basePath + "{*path}", null, constrasints, new ApiAccessRouteHandler())); }
public static bool TryParseRouteExpression(string expression, RouteValueDictionary routeValues, out string routeName) { routeName = null; if (string.IsNullOrEmpty(expression)) { return false; } foreach (string str in expression.Split(new char[] { ',' })) { string[] strArray2 = str.Split(new char[] { '=' }); if (strArray2.Length != 2) { return false; } string str2 = strArray2[0].Trim(); string str3 = strArray2[1].Trim(); if (string.IsNullOrEmpty(str2)) { return false; } if (str2.Equals("RouteName", StringComparison.OrdinalIgnoreCase)) { routeName = str3; } else { routeValues[str2] = str3; } } return true; }
/// <summary> /// The modal dialog action link. /// </summary> /// <param name="ajaxHelper">Um Helper Ajax.</param> /// <param name="linkText">O texto a ser exibido no link</param> /// <param name="actionName">A Action a ser executada quando o link for clicado</param> /// <param name="controllerName">O nome do controller</param> /// <param name="dialogTitle">O título do modal popUp a ser exibido</param> /// <param name="routeValues">Valores de Rota</param> /// <param name="htmlAttributes">html atributes</param> /// <param name="onSubmitJsCallback"> /// Um Callback JS a ser executado após o submit /// <para></para> /// Este callback deve ser criado de forma a receber uma conjunto de dados no formato Json. /// Ex: function callback(data){} /// Para informar quais dados devem ser submetidos, deve-se retornar um <see cref="DialogResult(System.Web.Mvc.Controller,string,object)"/>, /// endo o último parâmetro, um <see cref="object"/> que será serializado. /// Após a submissão do formulário, caso não seja especificado um callback, os dados serão descartados. /// </param> /// <returns>The <see cref="MvcHtmlString"/>.</returns> public static MvcHtmlString ModalDialogActionLink( this AjaxHelper ajaxHelper, string linkText, string actionName, string controllerName, string dialogTitle, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes, string onSubmitJsCallback) { if (routeValues == null) { routeValues = new RouteValueDictionary(); } var dialogDivId = Guid.NewGuid().ToString(); return ajaxHelper.ActionLink( linkText, actionName, controllerName, routeValues: routeValues, ajaxOptions: new AjaxOptions { UpdateTargetId = dialogDivId, InsertionMode = InsertionMode.Replace, HttpMethod = "GET", OnBegin = string.Format(CultureInfo.InvariantCulture, "prepareModalDialog('{0}')", dialogDivId), OnFailure = string.Format(CultureInfo.InvariantCulture, "clearModalDialog('{0}');alert('Ajax call failed')", dialogDivId), OnSuccess = string.Format(CultureInfo.InvariantCulture, "openModalDialog('{0}', '{1}', {2})", dialogDivId, dialogTitle, onSubmitJsCallback) }, htmlAttributes: htmlAttributes); }
public AuthorizationContext GetAuthorizationContext(RequestContext requestContext, string controllerName, string actionName, RouteValueDictionary routeValues) { object area; string areaName = string.Empty; string key = controllerName + " " + actionName; if (routeValues != null && routeValues.TryGetValue("Area", out area)) { areaName = area.ToString(); key = areaName + " " + key; } AuthorizationContext authorizationContext = cache.Get(key, () => AuthorizationContextFactory(requestContext, controllerName, actionName, areaName)); if (authorizationContext == null) { return null; } authorizationContext.RequestContext = requestContext; authorizationContext.HttpContext = requestContext.HttpContext; authorizationContext.Result = null; return authorizationContext; }
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { VirtualPathData path = base.GetVirtualPath(requestContext, values); if (path != null) { string virtualPath = path.VirtualPath; var lastIndexOf = virtualPath.LastIndexOf("?"); if (lastIndexOf != 0) { if (lastIndexOf > 0) { string leftPart = virtualPath.Substring(0, lastIndexOf).ToLowerInvariant(); string queryPart = virtualPath.Substring(lastIndexOf); path.VirtualPath = leftPart + queryPart; } else { path.VirtualPath = path.VirtualPath.ToLowerInvariant(); } } } return path; }
protected RedirectResult RedirectToAction <T>(Expression <Action <T> > action, RouteValueDictionary values = null) where T : Controller { return(new RedirectResult(RedirectionHelper.GetUrl(action, Request.RequestContext, values))); }
public FormContainer BeginForm(string actionName, string controllerName, RouteValueDictionary routeValues, BootstrapFormType formType = BootstrapFormType.Horizontal) { return(BeginForm(actionName, controllerName, routeValues, FormMethod.Post, new RouteValueDictionary(), formType)); }
public static RouteValueDictionary ExcludeNull(this RouteValueDictionary source) { return(source.ExcludeBy(x => x.Value == null)); }
public static RouteValueDictionary ExcludeUnusedIn(this RouteValueDictionary source, string routeUrl) { return(source.ExcludeBy(x => routeUrl.HasNoRouteKey(x.Key))); }
/// <inheritdoc /> /// <remarks>Does nothing if user provides an <c>href</c> attribute.</remarks> /// <exception cref="InvalidOperationException"> /// Thrown if <c>href</c> attribute is provided and <see cref="Action"/>, <see cref="Controller"/>, /// <see cref="Fragment"/>, <see cref="Host"/>, <see cref="Protocol"/>, or <see cref="Route"/> are /// non-<c>null</c> or if the user provided <c>asp-route-*</c> attributes. Also thrown if <see cref="Route"/> /// and one or both of <see cref="Action"/> and <see cref="Controller"/> are non-<c>null</c>. /// </exception> public override void Process(TagHelperContext context, TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } // If "href" is already set, it means the user is attempting to use a normal anchor. if (output.Attributes.ContainsName(Href)) { if (Action != null || Controller != null || Area != null || Route != null || Protocol != null || Host != null || Fragment != null || (_routeValues != null && _routeValues.Count > 0)) { // User specified an href and one of the bound attributes; can't determine the href attribute. throw new InvalidOperationException( Resources.FormatAnchorTagHelper_CannotOverrideHref( "<a>", ActionAttributeName, ControllerAttributeName, AreaAttributeName, RouteAttributeName, ProtocolAttributeName, HostAttributeName, FragmentAttributeName, RouteValuesPrefix, Href)); } } else { RouteValueDictionary routeValues = null; if (_routeValues != null && _routeValues.Count > 0) { routeValues = new RouteValueDictionary(_routeValues); } if (Area != null) { if (routeValues == null) { routeValues = new RouteValueDictionary(); } // Unconditionally replace any value from asp-route-area. routeValues["area"] = Area; } TagBuilder tagBuilder; if (Route == null) { tagBuilder = Generator.GenerateActionLink( ViewContext, linkText: string.Empty, actionName: Action, controllerName: Controller, protocol: Protocol, hostname: Host, fragment: Fragment, routeValues: routeValues, htmlAttributes: null); } else if (Action != null || Controller != null) { // Route and Action or Controller were specified. Can't determine the href attribute. throw new InvalidOperationException( Resources.FormatAnchorTagHelper_CannotDetermineHrefRouteActionOrControllerSpecified( "<a>", RouteAttributeName, ActionAttributeName, ControllerAttributeName, Href)); } else { tagBuilder = Generator.GenerateRouteLink( ViewContext, linkText: string.Empty, routeName: Route, protocol: Protocol, hostName: Host, fragment: Fragment, routeValues: routeValues, htmlAttributes: null); } if (tagBuilder != null) { output.MergeAttributes(tagBuilder); } } }
public void AddConventionalLinkGenerationRoute( List <Endpoint> endpoints, HashSet <string> routeNames, HashSet <string> keys, ConventionalRouteEntry route, IReadOnlyList <Action <EndpointBuilder> > conventions) { if (endpoints == null) { throw new ArgumentNullException(nameof(endpoints)); } if (keys == null) { throw new ArgumentNullException(nameof(keys)); } if (conventions == null) { throw new ArgumentNullException(nameof(conventions)); } var requiredValues = new RouteValueDictionary(); foreach (var key in keys) { if (route.Pattern.GetParameter(key) != null) { // Parameter (allow any) requiredValues[key] = RoutePattern.RequiredValueAny; } else if (route.Pattern.Defaults.TryGetValue(key, out var value)) { requiredValues[key] = value; } else { requiredValues[key] = null; } } // We have to do some massaging of the pattern to try and get the // required values to be correct. var pattern = _routePatternTransformer.SubstituteRequiredValues(route.Pattern, requiredValues); if (pattern == null) { // We don't expect this to happen, but we want to know if it does because it will help diagnose the bug. throw new InvalidOperationException("Failed to create a conventional route for pattern: " + route.Pattern); } var builder = new RouteEndpointBuilder(context => Task.CompletedTask, pattern, route.Order) { DisplayName = "Route: " + route.Pattern.RawText, Metadata = { new SuppressMatchingMetadata(), }, }; if (route.RouteName != null) { builder.Metadata.Add(new RouteNameMetadata(route.RouteName)); } // See comments on the other usage of EndpointNameMetadata in this class. // // The set of cases for a conventional route are much simpler. We don't need to check // for Endpoint Name already exising here because there's no way to add an attribute to // a conventional route. if (route.RouteName != null && routeNames.Add(route.RouteName)) { builder.Metadata.Add(new EndpointNameMetadata(route.RouteName)); } for (var i = 0; i < conventions.Count; i++) { conventions[i](builder); } for (var i = 0; i < route.Conventions.Count; i++) { route.Conventions[i](builder); } endpoints.Add((RouteEndpoint)builder.Build()); }
/// <summary> /// GetVirtualPath /// </summary> /// <param name="requestContext"></param> /// <param name="values"></param> /// <returns></returns> public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values) { return(null); }
public FormContainer BeginForm(RouteValueDictionary routeValues, BootstrapFormType formType = BootstrapFormType.Horizontal) { return(BeginForm(null, null, routeValues, FormMethod.Post, new RouteValueDictionary(), formType)); }
/// <inheritdoc /> /// <remarks>Does nothing if user provides an <c>FormAction</c> attribute.</remarks> /// <exception cref="InvalidOperationException"> /// Thrown if <c>FormAction</c> attribute is provided and <see cref="Action"/>, <see cref="Controller"/>, /// <see cref="Fragment"/> or <see cref="Route"/> are non-<c>null</c> or if the user provided <c>asp-route-*</c> attributes. /// Also thrown if <see cref="Route"/> and one or both of <see cref="Action"/> and <see cref="Controller"/> /// are non-<c>null</c> /// </exception> public override void Process(TagHelperContext context, TagHelperOutput output) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (output == null) { throw new ArgumentNullException(nameof(output)); } // If "FormAction" is already set, it means the user is attempting to use a normal button or input element. if (output.Attributes.ContainsName(FormAction)) { if (Action != null || Controller != null || Area != null || Page != null || PageHandler != null || Fragment != null || Route != null || (_routeValues != null && _routeValues.Count > 0)) { // User specified a FormAction and one of the bound attributes; can't override that FormAction // attribute. throw new InvalidOperationException( Resources.FormatFormActionTagHelper_CannotOverrideFormAction( FormAction, output.TagName, RouteValuesPrefix, ActionAttributeName, ControllerAttributeName, AreaAttributeName, FragmentAttributeName, RouteAttributeName, PageAttributeName, PageHandlerAttributeName)); } return; } var routeLink = Route != null; var actionLink = Controller != null || Action != null; var pageLink = Page != null || PageHandler != null; if ((routeLink && actionLink) || (routeLink && pageLink) || (actionLink && pageLink)) { var message = string.Join( Environment.NewLine, Resources.FormatCannotDetermineAttributeFor(FormAction, '<' + output.TagName + '>'), RouteAttributeName, ControllerAttributeName + ", " + ActionAttributeName, PageAttributeName + ", " + PageHandlerAttributeName); throw new InvalidOperationException(message); } RouteValueDictionary routeValues = null; if (_routeValues != null && _routeValues.Count > 0) { routeValues = new RouteValueDictionary(_routeValues); } if (Area != null) { if (routeValues == null) { routeValues = new RouteValueDictionary(); } // Unconditionally replace any value from asp-route-area. routeValues["area"] = Area; } var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); string url; if (pageLink) { url = urlHelper.Page(Page, PageHandler, routeValues, protocol: null, host: null, fragment: Fragment); } else if (routeLink) { url = urlHelper.RouteUrl(Route, routeValues, protocol: null, host: null, fragment: Fragment); } else { url = urlHelper.Action(Action, Controller, routeValues, protocol: null, host: null, fragment: Fragment); } output.Attributes.SetAttribute(FormAction, url); }
/// <summary> /// Gets a route for provider configuration /// </summary> /// <param name="actionName">Action name</param> /// <param name="controllerName">Controller name</param> /// <param name="routeValues">Route values</param> public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues) { actionName = "Configure"; controllerName = "FixedRate"; routeValues = new RouteValueDictionary() { { "area", "cloudCommerce.Shipping" } }; }
private bool MatchComplexSegmentCore( TemplateSegment routeSegment, string requestSegment, IReadOnlyDictionary <string, object> defaults, RouteValueDictionary values, int indexOfLastSegmentUsed) { Debug.Assert(routeSegment != null); Debug.Assert(routeSegment.Parts.Count > 1); // Find last literal segment and get its last index in the string var lastIndex = requestSegment.Length; TemplatePart parameterNeedsValue = null; // Keeps track of a parameter segment that is pending a value TemplatePart lastLiteral = null; // Keeps track of the left-most literal we've encountered var outValues = new RouteValueDictionary(); while (indexOfLastSegmentUsed >= 0) { var newLastIndex = lastIndex; var part = routeSegment.Parts[indexOfLastSegmentUsed]; if (part.IsParameter) { // Hold on to the parameter so that we can fill it in when we locate the next literal parameterNeedsValue = part; } else { Debug.Assert(part.IsLiteral); lastLiteral = part; var startIndex = lastIndex - 1; // If we have a pending parameter subsegment, we must leave at least one character for that if (parameterNeedsValue != null) { startIndex--; } if (startIndex < 0) { return(false); } var indexOfLiteral = requestSegment.LastIndexOf( part.Text, startIndex, StringComparison.OrdinalIgnoreCase); if (indexOfLiteral == -1) { // If we couldn't find this literal index, this segment cannot match return(false); } // If the first subsegment is a literal, it must match at the right-most extent of the request URI. // Without this check if your route had "/Foo/" we'd match the request URI "/somethingFoo/". // This check is related to the check we do at the very end of this function. if (indexOfLastSegmentUsed == (routeSegment.Parts.Count - 1)) { if ((indexOfLiteral + part.Text.Length) != requestSegment.Length) { return(false); } } newLastIndex = indexOfLiteral; } if ((parameterNeedsValue != null) && (((lastLiteral != null) && (part.IsLiteral)) || (indexOfLastSegmentUsed == 0))) { // If we have a pending parameter that needs a value, grab that value int parameterStartIndex; int parameterTextLength; if (lastLiteral == null) { if (indexOfLastSegmentUsed == 0) { parameterStartIndex = 0; } else { parameterStartIndex = newLastIndex; Debug.Assert(false, "indexOfLastSegementUsed should always be 0 from the check above"); } parameterTextLength = lastIndex; } else { // If we're getting a value for a parameter that is somewhere in the middle of the segment if ((indexOfLastSegmentUsed == 0) && (part.IsParameter)) { parameterStartIndex = 0; parameterTextLength = lastIndex; } else { parameterStartIndex = newLastIndex + lastLiteral.Text.Length; parameterTextLength = lastIndex - parameterStartIndex; } } var parameterValueString = requestSegment.Substring(parameterStartIndex, parameterTextLength); if (string.IsNullOrEmpty(parameterValueString)) { // If we're here that means we have a segment that contains multiple sub-segments. // For these segments all parameters must have non-empty values. If the parameter // has an empty value it's not a match. return(false); } else { // If there's a value in the segment for this parameter, use the subsegment value outValues.Add(parameterNeedsValue.Name, parameterValueString); } parameterNeedsValue = null; lastLiteral = null; } lastIndex = newLastIndex; indexOfLastSegmentUsed--; } // If the last subsegment is a parameter, it's OK that we didn't parse all the way to the left extent of // the string since the parameter will have consumed all the remaining text anyway. If the last subsegment // is a literal then we *must* have consumed the entire text in that literal. Otherwise we end up matching // the route "Foo" to the request URI "somethingFoo". Thus we have to check that we parsed the *entire* // request URI in order for it to be a match. // This check is related to the check we do earlier in this function for LiteralSubsegments. if (lastIndex == 0 || routeSegment.Parts[0].IsParameter) { foreach (var item in outValues) { values.Add(item.Key, item.Value); } return(true); } return(false); }
public RouteValueDictionary Match(PathString path) { var i = 0; var pathTokenizer = new PathTokenizer(path); // Perf: We do a traversal of the request-segments + route-segments twice. // // For most segment-types, we only really need to any work on one of the two passes. // // On the first pass, we're just looking to see if there's anything that would disqualify us from matching. // The most common case would be a literal segment that doesn't match. // // On the second pass, we're almost certainly going to match the URL, so go ahead and allocate the 'values' // and start capturing strings. foreach (var requestSegment in pathTokenizer) { var routeSegment = Template.GetSegment(i++); if (routeSegment == null && requestSegment.Length > 0) { // If pathSegment is null, then we're out of route segments. All we can match is the empty // string. return(null); } else if (routeSegment.IsSimple && routeSegment.Parts[0].IsLiteral) { // This is a literal segment, so we need to match the text, or the route isn't a match. var part = routeSegment.Parts[0]; if (!requestSegment.Equals(part.Text, StringComparison.OrdinalIgnoreCase)) { return(null); } } else if (routeSegment.IsSimple && routeSegment.Parts[0].IsCatchAll) { // Nothing to validate for a catch-all - it can match any string, including the empty string. // // Also, a catch-all has to be the last part, so we're done. break; } else if (routeSegment.IsSimple && routeSegment.Parts[0].IsParameter) { // For a parameter, validate that it's a has some length, or we have a default, or it's optional. var part = routeSegment.Parts[0]; if (requestSegment.Length == 0 && !_hasDefaultValue[i] && !part.IsOptional) { // There's no value for this parameter, the route can't match. return(null); } } else { Debug.Assert(!routeSegment.IsSimple); // Don't attempt to validate a complex segment at this point other than being non-emtpy, // do it in the second pass. } } for (; i < Template.Segments.Count; i++) { // We've matched the request path so far, but still have remaining route segments. These need // to be all single-part parameter segments with default values or else they won't match. var routeSegment = Template.GetSegment(i); Debug.Assert(routeSegment != null); if (!routeSegment.IsSimple) { // If the segment is a complex segment, it MUST contain literals, and we've parsed the full // path so far, so it can't match. return(null); } var part = routeSegment.Parts[0]; if (part.IsLiteral) { // If the segment is a simple literal - which need the URL to provide a value, so we don't match. return(null); } if (part.IsCatchAll) { // Nothing to validate for a catch-all - it can match any string, including the empty string. // // Also, a catch-all has to be the last part, so we're done. break; } // If we get here, this is a simple segment with a parameter. We need it to be optional, or for the // defaults to have a value. Debug.Assert(routeSegment.IsSimple && part.IsParameter); if (!_hasDefaultValue[i] && !part.IsOptional) { // There's no default for this (non-optional) parameter so it can't match. return(null); } } // At this point we've very likely got a match, so start capturing values for real. var values = new RouteValueDictionary(); i = 0; foreach (var requestSegment in pathTokenizer) { var routeSegment = Template.GetSegment(i++); if (routeSegment.IsSimple && routeSegment.Parts[0].IsCatchAll) { // A catch-all captures til the end of the string. var part = routeSegment.Parts[0]; var captured = requestSegment.Buffer.Substring(requestSegment.Offset); if (captured.Length > 0) { values.Add(part.Name, captured); } else { // It's ok for a catch-all to produce a null value, so we don't check _hasDefaultValue. values.Add(part.Name, _defaultValues[i]); } // A catch-all has to be the last part, so we're done. break; } else if (routeSegment.IsSimple && routeSegment.Parts[0].IsParameter) { // A simple parameter captures the whole segment, or a default value if nothing was // provided. var part = routeSegment.Parts[0]; if (requestSegment.Length > 0) { values.Add(part.Name, requestSegment.ToString()); } else { if (_hasDefaultValue[i]) { values.Add(part.Name, _defaultValues[i]); } } } else if (!routeSegment.IsSimple) { if (!MatchComplexSegment(routeSegment, requestSegment.ToString(), Defaults, values)) { return(null); } } } for (; i < Template.Segments.Count; i++) { // We've matched the request path so far, but still have remaining route segments. We already know these // are simple parameters that either have a default, or don't need to produce a value. var routeSegment = Template.GetSegment(i); Debug.Assert(routeSegment != null); Debug.Assert(routeSegment.IsSimple); var part = routeSegment.Parts[0]; Debug.Assert(part.IsParameter); // It's ok for a catch-all to produce a null value if (_hasDefaultValue[i] || part.IsCatchAll) { values.Add(part.Name, _defaultValues[i]); } } // Copy all remaining default values to the route data foreach (var kvp in Defaults) { if (!values.ContainsKey(kvp.Key)) { values.Add(kvp.Key, kvp.Value); } } return(values); }
public static MvcHtmlString Chart(this HtmlHelper helper, string actionName, string controllerName, RouteValueDictionary routeValues, object htmlAttributes) { return(Chart(helper, actionName, controllerName, routeValues, new RouteValueDictionary(htmlAttributes))); }
public static MvcHtmlString Chart(this HtmlHelper helper, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary <string, object> htmlAttributes) { string imgUrl = UrlHelper.GenerateUrl(null, actionName, controllerName, routeValues, helper.RouteCollection, helper.ViewContext.RequestContext, false); var builder = new TagBuilder("img"); builder.MergeAttributes <string, object>(htmlAttributes); builder.MergeAttribute("src", imgUrl); return(MvcHtmlString.Create(builder.ToString())); }
private void AddActionDataToBuilder( EndpointBuilder builder, HashSet <string> routeNames, ActionDescriptor action, string routeName, RouteValueDictionary dataTokens, bool suppressLinkGeneration, bool suppressPathMatching, IReadOnlyList <Action <EndpointBuilder> > conventions, IReadOnlyList <Action <EndpointBuilder> > perRouteConventions) { // Add action metadata first so it has a low precedence if (action.EndpointMetadata != null) { foreach (var d in action.EndpointMetadata) { builder.Metadata.Add(d); } } builder.Metadata.Add(action); // MVC guarantees that when two of it's endpoints have the same route name they are equivalent. // // The case for this looks like: // // [HttpGet] // [HttpPost] // [Route("/Foo", Name = "Foo")] // public void DoStuff() { } // // However, Endpoint Routing requires Endpoint Names to be unique. // // We can use the route name as the endpoint name if it's not set. Note that there's no // attribute for this today so it's unlikley. Using endpoint name on a if (routeName != null && !suppressLinkGeneration && routeNames.Add(routeName) && builder.Metadata.OfType <IEndpointNameMetadata>().LastOrDefault()?.EndpointName == null) { builder.Metadata.Add(new EndpointNameMetadata(routeName)); } if (dataTokens != null) { builder.Metadata.Add(new DataTokensMetadata(dataTokens)); } builder.Metadata.Add(new RouteNameMetadata(routeName)); // Add filter descriptors to endpoint metadata if (action.FilterDescriptors != null && action.FilterDescriptors.Count > 0) { foreach (var filter in action.FilterDescriptors.OrderBy(f => f, PublicFilterDescriptorOrderComparer.Comparer).Select(f => f.Filter)) { builder.Metadata.Add(filter); } } if (action.ActionConstraints != null && action.ActionConstraints.Count > 0) { // We explicitly convert a few types of action constraints into MatcherPolicy+Metadata // to better integrate with the DFA matcher. // // Other IActionConstraint data will trigger a back-compat path that can execute // action constraints. foreach (var actionConstraint in action.ActionConstraints) { if (actionConstraint is HttpMethodActionConstraint httpMethodActionConstraint && !builder.Metadata.OfType <HttpMethodMetadata>().Any()) { builder.Metadata.Add(new HttpMethodMetadata(httpMethodActionConstraint.HttpMethods)); } else if (actionConstraint is ConsumesAttribute consumesAttribute && !builder.Metadata.OfType <IPublicConsumesMetadata>().Any()) { builder.Metadata.Add(new PublicConsumesMetadata(consumesAttribute.ContentTypes.ToArray())); }
public static MvcHtmlString Chart(this HtmlHelper helper, string actionName, string controllerName, RouteValueDictionary routeValues) { return(Chart(helper, actionName, controllerName, routeValues, null)); }
/// <summary> /// Invoke regulated action to know if the request can be honored. /// </summary> /// <typeparam name="TController">Controller that contains the action.</typeparam> /// <param name="helper">Helper representation of @Url.</param> /// <param name="action">Action on which rights will be tested.</param> /// <param name="routeValues">Additional route value params.</param> /// <param name="protocol">The protocol.</param> /// <returns>String representation of the controller action URL.</returns> public static string RegulatedAction <TController>(this UrlHelper helper, Expression <Action <TController> > action, RouteValueDictionary routeValues, string protocol) { return(helper.RegulatedAction(action, routeValues, protocol, null)); }
/// <summary> /// Gets a route for provider configuration /// </summary> /// <param name="actionName">Action name</param> /// <param name="controllerName">Controller name</param> /// <param name="routeValues">Route values</param> public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues) { actionName = "Configure"; controllerName = "FeedFroogle"; routeValues = new RouteValueDictionary { { "Namespaces", "Grand.Plugin.Feed.Froogle.Controllers" }, { "area", null } }; }
/// <summary> /// Initializes a new instance of the <see cref="RoutedMenuItem" /> class. /// </summary> /// <param name="name"> Name (HTML id). </param> /// <param name="title"> Title shown for user. </param> /// <param name="route"> The route. </param> /// <example> /// <code>mainMenu.Add(new RoutedMenuItem("mnuUsers", "List users", new { controller = "User", action = "Index" });</code> /// </example> /// <remarks> /// Add the route item "area" for area routes /// </remarks> public RoutedMenuItem(string name, string title, object route) { _route = new RouteValueDictionary(route); Name = name; Title = title; }
public static Route IgnoreRoute(this RouteCollection routes, string name, string match, RouteValueDictionary constraints) { var route = new Route(match, new StopRoutingHandler()) { Constraints = constraints }; routes.Add(name, route); return(route); }
public SiteMapNode() { RouteValues = new RouteValueDictionary(); ChildNodes = new List <SiteMapNode>(); }
public static Route MapRoute(this RouteCollection routes, string name, string match, RouteValueDictionary defaults) { var route = new Route(match, new MvcRouteHandler()) { Defaults = defaults }; routes.Add(name, route); return(route); }
/// <summary> /// Invoke regulated action to know if the request can be honored. /// </summary> /// <typeparam name="TController">Controller that contains the action.</typeparam> /// <param name="helper">Helper representation of @Url.</param> /// <param name="action">Action on which rights will be tested.</param> /// <param name="routeValues">Additional route value params.</param> /// <param name="protocol">The protocol.</param> /// <param name="hostName">The hostname.</param> /// <returns>String representation of the controller action URL.</returns> public static string RegulatedAction <TController>(this UrlHelper helper, Expression <Action <TController> > action, RouteValueDictionary routeValues, string protocol, string hostName) { if (!RegulatedActionManager.IsAuthorized(action)) { return(String.Empty); } return(helper.Action((action.Body as MethodCallExpression).Method.Name, typeof(TController).Name.Replace("Controller", ""), routeValues, protocol, hostName)); }
/// <summary> /// Gets a route for provider configuration /// </summary> /// <param name="actionName">Action name</param> /// <param name="controllerName">Controller name</param> /// <param name="routeValues">Route values</param> public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues) { actionName = "Configure"; controllerName = "USPS"; routeValues = new RouteValueDictionary() { { "area", "SmartStore.USPS" } }; }
/// <summary> /// Invoke regulated action to know if the request can be honored. /// </summary> /// <typeparam name="TController">Controller that contains the action.</typeparam> /// <param name="helper">Helper representation of @Url.</param> /// <param name="action">Action on which rights will be tested.</param> /// <param name="routeValues">Additional route value params.</param> /// <param name="protocol">The protocol.</param> /// <returns>String representation of the controller action URL.</returns> public static string RegulatedAction <TController>(this UrlHelper helper, Expression <Action <TController> > action, object routeValues, string protocol) { var routeValueDictionnary = new RouteValueDictionary(routeValues); return(helper.RegulatedAction(action, routeValueDictionnary, protocol, null)); }
public override bool ProcessOutbound(HttpContext httpContext, RouteValueDictionary values) { return(Process(httpContext, values)); }