代码之家  ›  专栏  ›  技术社区  ›  Darin Dimitrov

如何正确编码anchor hrefs

  •  4
  • Darin Dimitrov  · 技术社区  · 15 年前

    在xhtml/strict文档中,如何正确编码定位标记中的URL:

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

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

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

    在哪里? CustomEncode 将被定义。

    我把这个问题贴上了标签 asp.net-mvc 因为我提出了以下问题。假设由我尝试的模板生成的默认路由:

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

    两者都呈现为

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

    虽然

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

    呈现为

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

    起初我觉得这是正确的,但当我点击链接时,我收到错误400错误的请求。

    我把这个放在同一个页面上测试id参数是否正确传递:

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

    答案也可能是为了搜索引擎优化而简单地避免在URL中使用这些字符。如果是这样的话,我会简单地避开他们,但我只是好奇CMS和博客如何处理这个问题。

    例如关于so的问题标题,例如 a/b 将渲染为 a-b 在anchor href中,我想这里有一些定制的东西,我正在寻找最佳实践。

    1 回复  |  直到 15 年前
        1
  •  2
  •   Community CDub    7 年前

    我做到了 this way 从Jeff Atwood用于堆栈溢出的内容中提取。