Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly encode anchor hrefs

What is the proper way to encode URLs in anchor tags in an XHTML/Strict document:

<a href="http://www.sit.com/page/<%= HttpUtility.UrlEncode("String that might contain unicode and dangerous characters like +, /, \\, <, >, \", ', =") %>">
    Anchor text
</a>

or

<a href="http://www.site.com/page/<%= HttpUtility.HtmlEncode("String that might contain unicode and dangerous characters like +, /, \\, <, >, \", ', =") %>">
    Anchor text
</a>

or

<a href="http://www.site.com/page/<%= CustomEncode("String that might contain unicode and dangerous characters like +, /, \\, <, >, \", ', =") %>">
    Anchor text
</a>

where CustomEncode is to be defined.

I've tagged the question with asp.net-mvc because I've come up with the following problem. Assuming the default route generated by the template I've tried:

<%= Html.RouteLink("action text", new { id ="a/b" }) %>
<%= Html.RouteLink("action text", new { id = Html.Encode("a/b") }) %>

which both render as

<a href="/Home/Index/a/b">action text</a>

while

<%= Html.RouteLink("action text", new { id = Url.Encode("a/b") }) %> 

renders as

<a href="/Home/Index/a%252fb">action text</a>

which at first seemed correct to me but when I click on the link I get error 400 Bad Request.

I put this on the same page to test if the id parameter is correctly passed:

<% if (ViewContext.RouteData.Values.ContainsKey("id")) { %>
    <div><%= Html.Encode(ViewContext.RouteData.Values["id"]) %></div>
<% } %>

The answer might also be to simply avoid these characters in urls for SEO purposes. If this is the case I would simply avoid them but I was just curious how do CMS and blogs handle this.

For example on SO question title such as a/b would render as a-b in the anchor href, so I guess there's some custom thing going on here and I am looking for best practices.

like image 257
Darin Dimitrov Avatar asked Nov 06 '22 16:11

Darin Dimitrov


1 Answers

I do it this way, picked up from something that Jeff Atwood uses for Stack Overflow.

like image 91
George Stocker Avatar answered Nov 15 '22 05:11

George Stocker