【问题标题】:HttpUtility.HtmlEncode() do not work in asp.net TextBox control?HttpUtility.HtmlEncode() 在 asp.net TextBox 控件中不起作用?
【发布时间】:2013-07-06 02:45:59
【问题描述】:

我的代码如下:

Test.aspx:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <input type="text" value="<%=HttpUtility.HtmlEncode(ab)%>" runat="server"/>
    </form>
</body>
</html>

Test.cs:

 public partial class Test: System.Web.UI.Page
    {
       public string ab;
        protected void Page_Load(object sender, EventArgs e)
        {
             ab = "<script>alert('111');</script>";
        }
    }

运行test.aspx页面后,文本框值为&lt;%=HttpUtility.HtmlEncode(ab)%&gt;

但是去掉runat="server"字符串显示正确!

【问题讨论】:

标签: asp.net


【解决方案1】:

当你对一个控件做runat="server"时,它变成了一个服务器控件而不是传统的HTML标签,所以属性是在服务器上处理的。不幸的是,这意味着内联脚本标签并不总是按照您的意愿行事。

你可以做一些事情。要么像你说的那样离开runat="server",这使它完全按照你想要的方式呈现,或者在代码中设置值:

myTextBox.Value = "whatever";

你也可以使用数据绑定,但是有点丑:

<input id="myTextBox" runat="server" type="text"
    value='<%# HttpUtility.HtmlEncode("someString") %>' />

protected void Page_Load(object sender, EventArgs e) {
    myTextBox.DataBind();
}

【讨论】:

  • @JoeEnos-感谢您的回复!假设在代码中设置值 myTextBox.Value="";有XSS攻击吗?
  • 如果您是在响应中添加文本的人,并且您知道它是安全的,那么您就可以了。 XSS 更多的是关于当您让用户发布某些内容时会发生什么,然后这些内容将显示在不同用户的响应中。例如,在论坛中,如果您允许某人发布文本,并且该文本向公众显示,那么您必须处理该文本的清理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-17
  • 2015-04-09
  • 2014-04-08
  • 2012-02-09
相关资源
最近更新 更多