5

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.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    "I was just curious how do CMS and blogs handle this." By stripping them, usually. Blog slugs almost never encode. It defeats the whole purpose of the slug, which is to be readable by humans. – Craig Stuntz Feb 23 '10 at 18:48
  • @Craig this seems very reasonable. Other than maintaining a dictionary with *removable* characters is there something built into the framework that would allow me to easily encode such urls or maybe some third party API? – Darin Dimitrov Feb 23 '10 at 18:49
  • Off the top of my head, I don't know. – Craig Stuntz Feb 23 '10 at 20:24

1 Answers1

2

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

Community
  • 1
  • 1
George Stocker
  • 57,289
  • 29
  • 176
  • 237