【问题标题】:dealing with nested quotes in html generated from c#处理从 c# 生成的 html 中的嵌套引号
【发布时间】:2011-01-14 11:27:57
【问题描述】:

我正在使用第 3 方库来显示工具提示,如下所示:

string tooltip = "test";
output.Write("onmouseover='Tip(\"" + test + "\");'");  // work fine :)

我遇到了以下情况,我需要引号来格式化:

string tooltip = "<span style='color:red;'>test</span>";
output.Write("onmouseover='Tip(\"" + test + "\");'");  // no working :(

如何在工具提示中转义 html 所需的引号,以免中断函数调用?

【问题讨论】:

    标签: c# html formatting quotes


    【解决方案1】:

    " 的任何实例替换为&amp;quot;,如下所示:

    test.Replace( "\"", "&quot;" )
    

    【讨论】:

    • 这仍然会导致 XSS 攻击。
    • 我认为您错误地假设字符串测试以某种方式来自最终用户,这不是我从上面的示例中看到的。对我来说,很明显他控制了工具提示。
    【解决方案2】:

    这是微软Anti-Xss Library的完美使用

    使用它,您可以调用 JavaScriptEncode 函数,该函数将构建一个如下所示的字符串:

    Microsoft.Security.Application.AntiXss.JavaScriptEncode("ab'c\"d")
    // 'ab\x27c\x22d'
    

    请注意其中包含引号

    您可以接受它,对其进行 HTML 编码,然后将其直接放入括号中。

    类似这样的:

    string tooltip = "<span style='color:red;'>test</span>";
    output.Write("onmouseover=\"Tip(" + AntiXss.JavaScriptEncode(test) + ");\"");  // working :)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-18
      • 2013-09-21
      • 2011-03-03
      • 2014-11-14
      • 2015-03-29
      • 1970-01-01
      • 2017-09-19
      相关资源
      最近更新 更多