Skip to content

Commit abeedd5

Browse files
author
Warren Buckley
committed
Use Uri.TryCreate to always get the path be it an absolute or relative path
1 parent 2a51693 commit abeedd5

File tree

1 file changed

+19
-17
lines changed

1 file changed

+19
-17
lines changed

Our.Umbraco.TagHelpers/IsActivePageTagHelper.cs

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using Umbraco.Cms.Core.Web;
44
using Umbraco.Extensions;
55
using Microsoft.AspNetCore.Mvc.TagHelpers;
6+
using System;
67

78
namespace Our.Umbraco.TagHelpers
89
{
@@ -31,7 +32,7 @@ public IsActivePageTagHelper(IUmbracoContextAccessor umbracoContextAccessor)
3132
/// </summary>
3233
[HtmlAttributeName(tagHelperAttributeName)]
3334
public string ActiveClassName { get; set; }
34-
35+
3536
public override void Process(TagHelperContext context, TagHelperOutput output)
3637
{
3738
// Remove the attribute
@@ -47,25 +48,26 @@ public override void Process(TagHelperContext context, TagHelperOutput output)
4748
return;
4849
}
4950

50-
// Clean href values of any querystrings
51-
// As we won't be able to query GetByRoute for an Umbraco node with them
52-
href = href.Substring(0, href.IndexOf("?") > 0 ? href.IndexOf("?") : href.Length);
53-
54-
// Get the node based of the value in the HREF
55-
var nodeOfLink = ctx.Content.GetByRoute(href);
56-
if(nodeOfLink == null)
51+
// Try & parse href as URI, as it could be relative or absolute
52+
// or contain a quersystring we only want the path part
53+
if (Uri.TryCreate(href, UriKind.Absolute, out Uri link) || Uri.TryCreate(ctx.PublishedRequest.Uri, href, out link))
5754
{
58-
return;
59-
}
55+
// Get the node based of the value in the HREF
56+
var nodeOfLink = ctx.Content.GetByRoute(link.AbsolutePath);
57+
if (nodeOfLink == null)
58+
{
59+
return;
60+
}
6061

61-
// Get the current node of the page that is rendering
62-
var currentPageRendering = ctx.PublishedRequest.PublishedContent;
62+
// Get the current node of the page that is rendering
63+
var currentPageRendering = ctx.PublishedRequest.PublishedContent;
6364

64-
// Check if thelink we are rendering is current page or an ancestor
65-
if(nodeOfLink.IsAncestorOrSelf(currentPageRendering))
66-
{
67-
// Is active page
68-
output.AddClass(ActiveClassName, HtmlEncoder.Default);
65+
// Check if thelink we are rendering is current page or an ancestor
66+
if (nodeOfLink.IsAncestorOrSelf(currentPageRendering))
67+
{
68+
// Is active page
69+
output.AddClass(ActiveClassName, HtmlEncoder.Default);
70+
}
6971
}
7072
}
7173
}

0 commit comments

Comments
 (0)