private void ProcessAsset(TagHelperOutput output) { if (string.IsNullOrEmpty(Src)) { return; } var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); if (!urlHelper.IsLocalUrl(Src)) { output.Attributes.SetAttribute(SRC_ATTRIBUTE_NAME, Src); return; } //remove the application path from the generated URL if exists var pathBase = ViewContext.HttpContext?.Request?.PathBase ?? PathString.Empty; PathString.FromUriComponent(Src).StartsWithSegments(pathBase, out var sourceFile); if (!_assetPipeline.TryGetAssetFromRoute(sourceFile, out var asset)) { asset = _assetPipeline.AddJavaScriptBundle(sourceFile, sourceFile); } output.Attributes.SetAttribute(SRC_ATTRIBUTE_NAME, $"{Src}?v={asset.GenerateCacheKey(ViewContext.HttpContext)}"); }
/// <summary> /// Tries to resolve the given <paramref name="url"/> value relative to the application's 'webroot' setting. /// </summary> /// <param name="url">The URL to resolve.</param> /// <param name="resolvedUrl"> /// Absolute URL beginning with the application's virtual root. <c>null</c> if <paramref name="url"/> could /// not be resolved. /// </param> /// <returns><c>true</c> if the <paramref name="url"/> could be resolved; <c>false</c> otherwise.</returns> protected bool TryResolveUrl(string url, out IHtmlContent resolvedUrl) { resolvedUrl = null; var start = FindRelativeStart(url); if (start == -1) { return(false); } var trimmedUrl = CreateTrimmedString(url, start); var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); var appRelativeUrl = urlHelper.Content(trimmedUrl); var postTildeSlashUrlValue = trimmedUrl.Substring(2); if (!appRelativeUrl.EndsWith(postTildeSlashUrlValue, StringComparison.Ordinal)) { throw new InvalidOperationException( Resources.FormatCouldNotResolveApplicationRelativeUrl_TagHelper( url, nameof(IUrlHelper), nameof(IUrlHelper.Content), "removeTagHelper", typeof(UrlResolutionTagHelper).FullName, typeof(UrlResolutionTagHelper).GetTypeInfo().Assembly.GetName().Name)); } resolvedUrl = new EncodeFirstSegmentContent( appRelativeUrl, appRelativeUrl.Length - postTildeSlashUrlValue.Length, postTildeSlashUrlValue); return(true); }
static public Link BeginLink( this IHtmlHelper html, string controllerName, string actionName, object routeValues, object htmlAttributes) { IUrlHelperFactory urlHelperFactory = new UrlHelperFactory(); string action; if (actionName == null && controllerName == null && routeValues == null) { var request = html.ViewContext.HttpContext.Request; action = request.PathBase + request.Path + request.QueryString; } else { var urlHelper = urlHelperFactory.GetUrlHelper(html.ViewContext); action = urlHelper.Action(action: actionName, controller: controllerName, values: routeValues); } var writer = html.ViewContext.Writer; TagBuilder linkCore = GenerateLinkCore(action, htmlAttributes); if (linkCore != null) { linkCore.TagRenderMode = TagRenderMode.StartTag; writer.WriteLine(linkCore); } return(new Link(writer)); }
public IUrlHelper GetUrlHelper(ActionContext context) { var originalUrlHelperFactory = new UrlHelperFactory(); var originalUrlHelper = originalUrlHelperFactory.GetUrlHelper(context); return(new CustomUrlHelper(context, originalUrlHelper, _urlRoutesOptions)); }
/// <summary> /// Tries to resolve the given <paramref name="url"/> value relative to the application's 'webroot' setting. /// </summary> /// <param name="url">The URL to resolve.</param> /// <param name="resolvedUrl"> /// Absolute URL beginning with the application's virtual root. <c>null</c> if <paramref name="url"/> could /// not be resolved. /// </param> /// <returns><c>true</c> if the <paramref name="url"/> could be resolved; <c>false</c> otherwise.</returns> protected bool TryResolveUrl(string url, out IHtmlContent resolvedUrl) { resolvedUrl = null; var start = FindRelativeStart(url); if (start == -1) { return(false); } url = url.Remove(start, 2).Insert(start, $"~/themes/{Theme.Key}/"); var trimmedUrl = CreateTrimmedString(url, start); var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); var appRelativeUrl = urlHelper.Content(trimmedUrl); var postTildeSlashUrlValue = trimmedUrl.Substring(2); if (!appRelativeUrl.EndsWith(postTildeSlashUrlValue, StringComparison.Ordinal)) { throw new InvalidOperationException(""); } resolvedUrl = new EncodeFirstSegmentContent( appRelativeUrl, appRelativeUrl.Length - postTildeSlashUrlValue.Length, postTildeSlashUrlValue); return(true); }
public void Activate_ActivatesAndContextualizesPropertiesOnViews() { // Arrange var modelMetadataProvider = new EmptyModelMetadataProvider(); var modelExpressionProvider = new ModelExpressionProvider(modelMetadataProvider, new ExpressionTextCache()); var urlHelperFactory = new UrlHelperFactory(); var jsonHelper = new JsonHelper( new JsonOutputFormatter(new JsonSerializerSettings(), ArrayPool <char> .Shared), ArrayPool <char> .Shared); var htmlEncoder = new HtmlTestEncoder(); var diagnosticSource = new DiagnosticListener("Microsoft.AspNetCore"); var activator = new RazorPageActivator( new EmptyModelMetadataProvider(), urlHelperFactory, jsonHelper, diagnosticSource, htmlEncoder, modelExpressionProvider); var instance = new TestRazorPage(); var myService = new MyService(); var helper = Mock.Of <IHtmlHelper <object> >(); var serviceProvider = new ServiceCollection() .AddSingleton(myService) .AddSingleton(helper) .AddSingleton(new ExpressionTextCache()) .BuildServiceProvider(); var httpContext = new DefaultHttpContext { RequestServices = serviceProvider }; var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); var viewContext = new ViewContext( actionContext, Mock.Of <IView>(), new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary()), Mock.Of <ITempDataDictionary>(), TextWriter.Null, new HtmlHelperOptions()); var urlHelper = urlHelperFactory.GetUrlHelper(viewContext); // Act activator.Activate(instance, viewContext); // Assert Assert.Same(helper, instance.Html); Assert.Same(myService, instance.MyService); Assert.Same(viewContext, myService.ViewContext); Assert.Same(diagnosticSource, instance.DiagnosticSource); Assert.Same(htmlEncoder, instance.HtmlEncoder); Assert.Same(jsonHelper, instance.Json); Assert.Same(urlHelper, instance.Url); Assert.Null(instance.MyService2); }
public virtual void Contextualize(ViewContext viewContext) { ViewContext = viewContext; UrlHelper = UrlHelperFactory.GetUrlHelper(viewContext); parents = (Stack <IWritableItem>)viewContext.HttpContext.Items[ParentStackContextKey]; if (parents == null) { parents = new Stack <IWritableItem>(5); parents.Push(null); viewContext.HttpContext.Items[ParentStackContextKey] = parents; } }
public override void Process(TagHelperContext context, TagHelperOutput output) { var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); output.Attributes.SetAttribute("href", urlHelper.Action(new UrlActionContext { Controller = Controller, Action = Action })); output.PreContent.SetContent($"{nameof(TestTagHelper)} content."); }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (AngHref != null) { string href = "{{" + AngHref.GetName() + "}}"; if (AngHrefRoute != null) { href = UrlHelperFactory.GetUrlHelper(ViewContext).Content(AngHrefRoute) + href; } href = $"{AngHrefPrefix}{href}{AngHrefSuffix}"; output.Attributes.SetAttribute("ng-href", href); } }
private string GetFormAction() { var routeLink = Route != null; var actionLink = Controller != null || Action != null; var pageLink = Page != null || PageHandler != null; // make local copy var routeValues = new RouteValueDictionary(RouteValues); // Unconditionally replace any value from asp-route-area. if (Area != null) { routeValues["area"] = Area; } var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); if (pageLink) { return(urlHelper.Page( Page, PageHandler, routeValues, protocol: null, host: null, fragment: Fragment)); } if (routeLink) { return(urlHelper.RouteUrl( Route, routeValues, protocol: null, host: null, fragment: Fragment)); } return(urlHelper.Action( Action, Controller, routeValues, protocol: null, host: null, fragment: Fragment)); }
public override void Process(TagHelperContext context, TagHelperOutput output) { base.Process(context, output); var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext) as FullUrlHelper; if (urlHelper == null) { return; } if (output.PostElement != null && !output.PostElement.IsEmptyOrWhiteSpace) { var content = output.PostElement.GetContent(); output.PostElement.SetHtmlContent(hrefRegex.Replace(content, match => "src=\"" + urlHelper.Content(match.Groups[1].Value) + "\"")); } }
public override void Process(TagHelperContext context, TagHelperOutput output) { if (Controller != null && Action != null) { var methodParameters = output.Attributes.ToDictionary(attribute => attribute.Name, attribute => attribute.Value); // We remove all attributes from the resulting HTML element because they're supposed to // be parameters to our final href value. output.Attributes.Clear(); var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); output.Attributes.SetAttribute("href", urlHelper.Action(Action, Controller, methodParameters)); output.PreContent.SetContent("My "); } }
public void AssignThumbnailUrl(FileSystemInfo fileSystemInfo, IClientFileSystemItem clientItem) { if (clientItem.IsDirectory || !CanGenerateThumbnail(fileSystemInfo)) { return; } if (!(fileSystemInfo is FileInfo fileInfo)) { return; } var helper = UrlHelperFactory.GetUrlHelper(ActionContextAccessor.ActionContext); var thumbnail = GetThumbnail(fileInfo); var relativeThumbnailPath = Path.Combine(ThumbnailsDirectory.Name, thumbnail.Directory?.Name, thumbnail.Name); clientItem.CustomFields["thumbnailUrl"] = helper.Content(relativeThumbnailPath); }
/// <summary> /// Tries to resolve the given <paramref name="url"/> value relative to the application's 'webroot' setting. /// </summary> /// <param name="url">The URL to resolve.</param> /// <param name="resolvedUrl">Absolute URL beginning with the application's virtual root. <c>null</c> if /// <paramref name="url"/> could not be resolved.</param> /// <returns><c>true</c> if the <paramref name="url"/> could be resolved; <c>false</c> otherwise.</returns> protected bool TryResolveUrl(string url, out string resolvedUrl) { resolvedUrl = null; var start = FindRelativeStart(url); if (start == -1) { return(false); } var trimmedUrl = CreateTrimmedString(url, start); var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); resolvedUrl = urlHelper.Content(trimmedUrl); return(true); }
public void GetUrlHelper_CreatesNewInstance_IfNotAlreadyPresent() { // Arrange var httpContext = new Mock <HttpContext>(); httpContext.SetupGet(h => h.Features).Returns(new FeatureCollection()); httpContext.Setup(h => h.Items).Returns(new Dictionary <object, object>()); var actionContext = CreateActionContext(httpContext.Object); var urlHelperFactory = new UrlHelperFactory(); // Act var urlHelper = urlHelperFactory.GetUrlHelper(actionContext); // Assert Assert.NotNull(urlHelper); Assert.Same(urlHelper, actionContext.HttpContext.Items[typeof(IUrlHelper)] as IUrlHelper); }
/// <summary> /// Tries to resolve the given <paramref name="url"/> value relative to the application's 'webroot' setting. /// </summary> /// <param name="url">The URL to resolve.</param> /// <param name="resolvedUrl">Absolute URL beginning with the application's virtual root. <c>null</c> if /// <paramref name="url"/> could not be resolved.</param> /// <returns><c>true</c> if the <paramref name="url"/> could be resolved; <c>false</c> otherwise.</returns> protected bool TryResolveUrl(string url, out string resolvedUrl) { resolvedUrl = null; var start = FindRelativeStart(url); if (start == -1) { return(false); } url = url.Remove(start, 2).Insert(start, $"~/themes/{Theme.Key}/"); var trimmedUrl = CreateTrimmedString(url, start); var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); resolvedUrl = urlHelper.Content(trimmedUrl); return(true); }
/// <summary> /// Tries to resolve the given <paramref name="url"/> value relative to the application's 'webroot' setting. /// </summary> /// <param name="url">The URL to resolve.</param> /// <param name="resolvedUrl">Absolute URL beginning with the application's virtual root. <c>null</c> if /// <paramref name="url"/> could not be resolved.</param> /// <returns><c>true</c> if the <paramref name="url"/> could be resolved; <c>false</c> otherwise.</returns> protected bool TryResolveUrl(string url, out string resolvedUrl) { resolvedUrl = null; if (url == null) { return(false); } var trimmedUrl = url.Trim(ValidAttributeWhitespaceChars); // Before doing more work, ensure that the URL we're looking at is app-relative. if (trimmedUrl.Length >= 2 && trimmedUrl[0] == '~' && trimmedUrl[1] == '/') { var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); resolvedUrl = urlHelper.Content(trimmedUrl); return(true); } return(false); }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { var actionContext = Accessor.ActionContext; var urlHelper = UrlHelperFactory.GetUrlHelper(actionContext); output.TagName = "ul"; var content = await output.GetChildContentAsync(); if (string.IsNullOrWhiteSpace(content.GetContent()) == false) { var tags = content.GetContent().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var sb = new StringBuilder(); foreach (var tag in tags) { sb.AppendFormat("<li class='d-inline p-1'><a href='{0}' class='btn btn-success'>{1}</a></li>", urlHelper.Page("index", "tag", new { tag = tag }), tag); } output.Content.SetHtmlContent(sb.ToString()); } }
/// <summary> /// Tries to resolve the given <paramref name="url"/> value relative to the application's 'webroot' setting. /// </summary> /// <param name="url">The URL to resolve.</param> /// <param name="resolvedUrl"> /// Absolute URL beginning with the application's virtual root. <c>null</c> if <paramref name="url"/> could /// not be resolved. /// </param> /// <returns><c>true</c> if the <paramref name="url"/> could be resolved; <c>false</c> otherwise.</returns> protected bool TryResolveUrl(string url, out IHtmlContent resolvedUrl) { resolvedUrl = null; if (url == null) { return(false); } var trimmedUrl = url.Trim(ValidAttributeWhitespaceChars); // Before doing more work, ensure that the URL we're looking at is app-relative. if (trimmedUrl.Length >= 2 && trimmedUrl[0] == '~' && trimmedUrl[1] == '/') { var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); var appRelativeUrl = urlHelper.Content(trimmedUrl); var postTildeSlashUrlValue = trimmedUrl.Substring(2); if (!appRelativeUrl.EndsWith(postTildeSlashUrlValue, StringComparison.Ordinal)) { throw new InvalidOperationException( Resources.FormatCouldNotResolveApplicationRelativeUrl_TagHelper( url, nameof(IUrlHelper), nameof(IUrlHelper.Content), "removeTagHelper", typeof(UrlResolutionTagHelper).FullName, typeof(UrlResolutionTagHelper).GetTypeInfo().Assembly.GetName().Name)); } resolvedUrl = new EncodeFirstSegmentContent( appRelativeUrl, appRelativeUrl.Length - postTildeSlashUrlValue.Length, postTildeSlashUrlValue); return(true); } return(false); }
public void GetUrlHelper_ReturnsSameInstance_IfAlreadyPresent() { // Arrange var expectedUrlHelper = CreateUrlHelper(); var httpContext = new Mock <HttpContext>(); httpContext.SetupGet(h => h.Features).Returns(new FeatureCollection()); var mockItems = new Dictionary <object, object> { { typeof(IUrlHelper), expectedUrlHelper } }; httpContext.Setup(h => h.Items).Returns(mockItems); var actionContext = CreateActionContext(httpContext.Object); var urlHelperFactory = new UrlHelperFactory(); // Act var urlHelper = urlHelperFactory.GetUrlHelper(actionContext); // Assert Assert.Same(expectedUrlHelper, urlHelper); }
public virtual async Task <RssChannel> GetChannel(CancellationToken cancellationToken = default(CancellationToken)) { var project = await ProjectService.GetCurrentProjectSettings(); if (project == null) { return(null); } var itemsToGet = project.DefaultFeedItems; var requestedFeedItems = ContextAccessor.HttpContext?.Request.Query["maxItems"].ToString(); if (!string.IsNullOrWhiteSpace(requestedFeedItems)) { int.TryParse(requestedFeedItems, out itemsToGet); if (itemsToGet > project.MaxFeedItems) { itemsToGet = project.MaxFeedItems; } } var posts = await BlogService.GetRecentPosts(itemsToGet); if (posts == null) { return(null); } var channel = new RssChannel { Title = project.Title, Copyright = project.CopyrightNotice, Generator = Name, RemoteFeedUrl = project.RemoteFeedUrl, RemoteFeedProcessorUseAgentFragment = project.RemoteFeedProcessorUseAgentFragment }; if (!string.IsNullOrEmpty(project.Description)) { channel.Description = project.Description; } else { // prevent error, channel desc cannot be empty channel.Description = "Welcome to my blog"; } if (!string.IsNullOrEmpty(project.ChannelCategoriesCsv)) { var channelCats = project.ChannelCategoriesCsv.Split(','); foreach (var cat in channelCats) { channel.Categories.Add(new RssCategory(cat)); } } var urlHelper = UrlHelperFactory.GetUrlHelper(ActionContextAccesor.ActionContext); if (!string.IsNullOrEmpty(project.Image)) { channel.Image.Url = new Uri(urlHelper.Content(project.Image)); } if (!string.IsNullOrEmpty(project.LanguageCode)) { channel.Language = new CultureInfo(project.LanguageCode); } var baseUrl = string.Concat( ContextAccessor.HttpContext.Request.Scheme, "://", ContextAccessor.HttpContext.Request.Host.ToUriComponent() ); // asp.net bug? the comments for this method say it returns an absolute fully qualified url but it returns relative // looking at latest code seems ok so maybe just a bug in rc1 //https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/UrlHelperExtensions.cs //https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/Routing/UrlHelper.cs var indexUrl = urlHelper.RouteUrl(BlogRoutes.BlogIndexRouteName); if (indexUrl == null) { indexUrl = urlHelper.Action("Index", "Blog"); } if (indexUrl.StartsWith("/")) { indexUrl = string.Concat(baseUrl, indexUrl); } channel.Link = new Uri(indexUrl); if (!string.IsNullOrEmpty(project.ManagingEditorEmail)) { channel.ManagingEditor = project.ManagingEditorEmail; } if (!string.IsNullOrEmpty(project.ChannelRating)) { channel.Rating = project.ChannelRating; } var feedUrl = string.Concat( ContextAccessor.HttpContext.Request.Scheme, "://", ContextAccessor.HttpContext.Request.Host.ToUriComponent(), ContextAccessor.HttpContext.Request.PathBase.ToUriComponent(), ContextAccessor.HttpContext.Request.Path.ToUriComponent(), ContextAccessor.HttpContext.Request.QueryString.ToUriComponent()); channel.SelfLink = new Uri(feedUrl); channel.TimeToLive = project.ChannelTimeToLive; if (!string.IsNullOrEmpty(project.WebmasterEmail)) { channel.Webmaster = project.WebmasterEmail; } DateTime mostRecentPubDate = DateTime.MinValue; var items = new List <RssItem>(); foreach (var post in posts) { if (!post.PubDate.HasValue) { continue; } if (post.PubDate.Value > mostRecentPubDate) { mostRecentPubDate = post.PubDate.Value; } var rssItem = new RssItem { Author = post.Author }; if (post.Categories.Count > 0) { foreach (var c in post.Categories) { rssItem.Categories.Add(new RssCategory(c)); } } var postUrl = await BlogUrlResolver.ResolvePostUrl(post, project).ConfigureAwait(false); if (string.IsNullOrEmpty(postUrl)) { //TODO: log continue; } if (postUrl.StartsWith("/")) { //postUrl = urlHelper.Content(postUrl); postUrl = string.Concat( ContextAccessor.HttpContext.Request.Scheme, "://", ContextAccessor.HttpContext.Request.Host.ToUriComponent(), postUrl); } var filteredResult = ContentProcessor.FilterHtmlForRss(post, project, baseUrl); rssItem.Description = filteredResult.FilteredContent; if (!filteredResult.IsFullContent) { //TODO: localize var readMore = " <a href='" + postUrl + "'>...read more</a>"; rssItem.Description += readMore; } //rssItem.Enclosures rssItem.Guid = new RssGuid(postUrl, true); rssItem.Link = new Uri(postUrl); rssItem.PublicationDate = post.PubDate.Value; //rssItem.Source rssItem.Title = post.Title; items.Add(rssItem); } channel.PublicationDate = mostRecentPubDate; channel.Items = items; return(channel); }
/// <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); }
/// <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"/> or <see cref="Fragment"/> are non-<c>null</c> /// or if the user provided <c>asp-route-*</c> attributes. /// </exception> public override void Process(TagHelperContext context, TagHelperOutput 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 is not null || Controller is not null || Area is not null || Page is not null || PageHandler is not null || Fragment is not null || Route is not null || (RouteValues is not null && RouteValues.Count > 0)) { // User specified a FormAction and one of the bound attributes // Can't override that FormAction attribute. throw new InvalidOperationException( CannotOverrideFormAction( FormAction, output.TagName, RouteValuesPrefix, ActionAttributeName, ControllerAttributeName, AreaAttributeName, FragmentAttributeName, RouteAttributeName, PageAttributeName, PageHandlerAttributeName)); } return; } var routeLink = Route is not null; var actionLink = Controller is not null || Action is not null; var pageLink = Page is not null || PageHandler is not null; if ((routeLink && actionLink) || (routeLink && pageLink) || (actionLink && pageLink)) { var message = string.Join( Environment.NewLine, FormatCannotDetermineAttributeFor(FormAction, '<' + output.TagName + '>'), RouteAttributeName, ControllerAttributeName + ", " + ActionAttributeName, PageAttributeName + ", " + PageHandlerAttributeName); throw new InvalidOperationException(message); } RouteValueDictionary?routeValues = null; if (RouteValues is not null && RouteValues.Count > 0) { routeValues = new RouteValueDictionary(RouteValues); } if (Area is not null) { if (routeValues is null) { routeValues = new RouteValueDictionary(); } // Unconditionally replace any value from asp-route-area. routeValues["area"] = Area; } var url = string.Empty; IUrlHelper?urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); 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 if (actionLink) { url = urlHelper.Action(Action, Controller, routeValues, null, null, Fragment); } if (string.IsNullOrEmpty(url) is false) { output.Attributes.SetAttribute(FormAction, url); } // Set the button appearance output.Attributes.SetAttribute(nameof(Appearance), Appearance.ToString().ToLowerInvariant()); output.Attributes.SetAttribute("type", "submit"); output.Attributes.SetAttribute(FormAction, url); }
/// <summary> /// Process TagHelper /// </summary> /// <param name="context">TagHelperContext</param> /// <param name="output">TagHelperOutput</param> public override void Process(TagHelperContext context, TagHelperOutput output) { // Return if no menu or items to output if (Menu is null || Menu.Items.Count == 0) { output.SuppressOutput(); return; } // Setup objects var currentController = ViewContext.ControllerName().ToLower(CultureInfo.InvariantCulture); var currentAction = ViewContext.ActionName().ToLower(CultureInfo.InvariantCulture); var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); // Build the menu BuildMenu( Menu.Items, mi => mi.Controller.ToLower(CultureInfo.InvariantCulture) == currentController, mi => mi.Controller, el => output.Content.AppendHtml(el) ); // Set output properties output.TagName = WrapperElement; output.TagMode = TagMode.StartTagAndEndTag; output.Attributes.Add("class", WrapperClass); // Build a menu (allows recursion for child menus) // // items: The menu items to build a menu for // isActive: Function which determines whether or not the current item is the active page // getText: If MenuItem.Text is null, returns the text to show in the link // append: Action to append the element to the menu wrapper void BuildMenu(List <MenuItem> items, Func <MenuItem, bool> isActive, Func <MenuItem, string> getText, Action <TagBuilder> append) { // Add each menu item to the menu foreach (var menuItem in items) { // Create item element var item = new TagBuilder(ItemElement); item.AddCssClass(ItemClass); // Create link element var link = new TagBuilder("a"); link.AddCssClass(LinkClass); // Add GUID link.MergeAttribute("id", $"link-{menuItem.Id}"); // Check whether or not this is an active link / section if (isActive(menuItem)) { link.AddCssClass(LinkActiveClass); } // Generate the link URL var urlActionContext = new UrlActionContext { Controller = menuItem.Controller, Action = menuItem.Action, Values = menuItem.RouteValues }; link.Attributes.Add("href", urlHelper.Action(urlActionContext)); // Add link text - if not set use getText() function _ = link.InnerHtml.Append(menuItem.Text ?? getText(menuItem)); // Add the link to the list item _ = item.InnerHtml.AppendHtml(link); // Check for child menu if (IncludeChildren && menuItem.Children.Count > 0) { // Create child menu wrapper var childMenu = new TagBuilder(WrapperElement); childMenu.AddCssClass(ChildMenuWrapperClass); // Build child menu BuildMenu( menuItem.Children, mi => mi.Action.ToLower(CultureInfo.InvariantCulture) == currentAction, mi => mi.Action, el => childMenu.InnerHtml.AppendHtml(el) ); // Add child menu to item _ = item.InnerHtml.AppendHtml(childMenu); } // Append item append(item); } } }
/// <summary> /// Generate the base URI used to calculate the final URL. /// </summary> /// <returns></returns> protected string GenerateBaseUri() { var helper = UrlHelperFactory.GetUrlHelper(ViewContext); return(helper.Action(Action, Controller, RouteValues, Protocol, Host, Fragment)); }
/// <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 || 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( output.TagName, ActionAttributeName, ControllerAttributeName, AreaAttributeName, FragmentAttributeName, RouteAttributeName, RouteValuesPrefix, FormAction)); } } 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; } if (Route == null) { var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); var url = urlHelper.Action(Action, Controller, routeValues, protocol: null, host: null, fragment: Fragment); output.Attributes.SetAttribute(FormAction, url); } else if (Action != null || Controller != null) { // Route and Action or Controller were specified. Can't determine the formaction attribute. throw new InvalidOperationException( Resources.FormatFormActionTagHelper_CannotDetermineFormActionRouteActionOrControllerSpecified( output.TagName, RouteAttributeName, ActionAttributeName, ControllerAttributeName, FormAction, FragmentAttributeName)); } else { var urlHelper = UrlHelperFactory.GetUrlHelper(ViewContext); var url = urlHelper.RouteUrl(Route, routeValues, protocol: null, host: null, fragment: Fragment); output.Attributes.SetAttribute(FormAction, url); } } }
public string GCU(string url) { var urlHelper = UrlHelperFactory.GetUrlHelper(this.ViewContext); return($"{Host}{urlHelper.Content(url)}"); }
public static IHtmlContent Pager(this IHtmlHelper htmlHelper, IPagedList pagedList, PagerOptions options) { TagBuilder pagerTagBuilder = new TagBuilder(options.TagName); if (!String.IsNullOrEmpty(options.Id)) { pagerTagBuilder.MergeAttribute("id", options.Id); } pagerTagBuilder.AddCssClass(options.CssClass); bool notShowPager = options.NoMorePageHide && (pagedList.MaxPageIndex == 1); if (notShowPager) { return(pagerTagBuilder); } UrlHelperFactory urlHelperFactory = new UrlHelperFactory(); var urlHelper = urlHelperFactory.GetUrlHelper(htmlHelper.ViewContext); #region Init Query Dic var ignoreCaseComparer = StringComparer.Create(System.Threading.Thread.CurrentThread.CurrentCulture, true); var dicQuery = new Dictionary <string, object>(ignoreCaseComparer); foreach (var item in htmlHelper.ViewContext.HttpContext.Request.Query) { dicQuery.Add(item.Key, item.Value); } if (dicQuery.ContainsKey(options.PageIndexParameterKey)) { dicQuery[options.PageIndexParameterKey] = 1; } else { dicQuery.Add(options.PageIndexParameterKey, 1); } #endregion #region FirstPage if (pagedList.CurrentPageIndex > 1) { var nextPageUrl = urlHelper.Link(options.RouteName, dicQuery); AddPageItem(pagerTagBuilder, options.TextTemplate, nextPageUrl, options.FirstText); } #endregion #region PrePage int prePageIndex = pagedList.CurrentPageIndex - 1; if (prePageIndex > 1) { dicQuery[options.PageIndexParameterKey] = prePageIndex; var prePageUrl = urlHelper.Link(options.RouteName, dicQuery); AddPageItem(pagerTagBuilder, options.TextTemplate, prePageUrl, options.PreText); } #endregion #region NumericalPage int startPageIndex = pagedList.CurrentPageIndex - options.PaddingPageNum; if (startPageIndex < 1) { startPageIndex = 1; } int endPageIndex = pagedList.CurrentPageIndex + options.PaddingPageNum; if (endPageIndex > pagedList.MaxPageIndex) { endPageIndex = pagedList.MaxPageIndex; } for (int pageIndex = startPageIndex; pageIndex <= endPageIndex; pageIndex++) { string template = options.ItemTemplate; if (pageIndex == pagedList.CurrentPageIndex) { template = options.CurrentTemplate; } dicQuery[options.PageIndexParameterKey] = pageIndex; string itemPageUrl = urlHelper.Link(options.RouteName, dicQuery); AddPageItem(pagerTagBuilder, template, itemPageUrl, pageIndex); } #endregion #region NextPage int nextPageIndex = pagedList.CurrentPageIndex + 1; if (nextPageIndex < pagedList.MaxPageIndex) { dicQuery[options.PageIndexParameterKey] = nextPageIndex; var nextPageUrl = urlHelper.Link(options.RouteName, dicQuery); AddPageItem(pagerTagBuilder, options.TextTemplate, nextPageUrl, options.NextText); } #endregion #region LastPage if (pagedList.CurrentPageIndex < pagedList.MaxPageIndex) { dicQuery[options.PageIndexParameterKey] = pagedList.MaxPageIndex; var lastPageUrl = urlHelper.Link(options.RouteName, dicQuery); AddPageItem(pagerTagBuilder, options.TextTemplate, lastPageUrl, options.LastText); } #endregion return(pagerTagBuilder); }