How to encode hrefs bindings correctly

What is the correct 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 should be defined.

I noted the asp.net-mvc question because I had the following problem. Assuming the default route created by the template I tried:

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

which both appear as

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

while

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

displayed as

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

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

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

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

The answer may also be to simply avoid these characters in the URLs for SEO purposes. If so, I would just have avoided them, but I was curious how to deal with CMS and blogs.

For example, a SO question name such as a/b will display as ab in the href anchor, so I assume some kind of ordinary thing happens here, and I'm looking for best practices.

+4
source share
1 answer

I do it this way , taken from something that Jeff Atwood uses for.

+2
source

Source: https://habr.com/ru/post/1302152/


All Articles