【问题标题】:A potentially dangerous Request.Form value was detected from the client : Which solution从客户端检测到潜在危险的 Request.Form 值:哪个解决方案
【发布时间】:2016-08-27 05:48:22
【问题描述】:

我有一个使用 aspx 页面的 Web 应用程序。 首先,我想在 LabelledTextBox 中显示值时使用 Server.HtmlEncode(value)

public interface ILabelledControl
{
    bool ReadOnly { get; set; }
}

[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class LabelledTextBox : TextBox, ILabelledControl
{
    //public Unit EditableWidth { get; set; }
    public Unit ReadOnlyWidth { get; set; }

    protected override void Render(System.Web.UI.HtmlTextWriter writer)
    {
        if (this.ReadOnly)
        {
            System.Web.UI.WebControls.Label lbl = new System.Web.UI.WebControls.Label();
            foreach (string att in this.Attributes.Keys)
                lbl.Attributes.Add(att, this.Attributes[att]);
            lbl.Text = this.Text;
            lbl.ForeColor = ForeColor;
            //lbl.Width = this.Width;
            if (ReadOnlyWidth != null)
                lbl.Width = ReadOnlyWidth;
            lbl.CssClass = CssClass;
            lbl.ID = this.ID;
            lbl.RenderControl(writer);
        }
        else
        {

            base.Render(writer);
        }
    }
}

&lt;script&gt;alert("hello")&lt;/script&gt;已显示,但脚本已执行。

之后,我想尝试另一种处理异常的解决方案

A potentially dangerous Request.Form value was detected from the client

停留在包含表单的同一页面上,并在顶部显示一条错误消息,其中包含一条通用消息,例如“请确保所有输入不包含''之类的字符”

解决方案 1:我做错了什么?

解决方案 2:如何处理此异常并与填写的表单保持在同一页面上

一般:哪种解决方案最好?

谢谢!

【问题讨论】:

    标签: asp.net validation exception xss html-encode


    【解决方案1】:

    从 客户

    您会看到此服务器异常,因为用户在 Textbox 控件中输入 HTML 标记(例如 )并提交表单。

    在服务器端没有什么可以阻止它的。但是,您可以创建客户端验证脚本,并警告用户或去除标签。

    例如,

    <asp:RegularExpressionValidator 
         ID="RegularExpressionValidator1" runat="server"    
         ControlToValidate="MyTextBox"
         ErrorMessage="Please do not enter HTML tags." 
         ValidationExpression="<(.|\n)*?>">
    </asp:RegularExpressionValidator>
    

    值 alert("hello") 已显示,但脚本 被处决了

    这与上述情况相反。服务器将 Script 标签呈现给浏览器。

    为了防止它,正如您所说,您想在渲染之前使用HttpServerUtility.HtmlEncode 对字符串进行编码。

    lbl.Text = Server.HtmlEncode(this.Text);
    

    【讨论】:

    • 1) 如何创建客户端验证?我应该删除哪些字符?有很多角色可能很危险,我错了吗? 2) 我尝试使用 HtmlEncode - 显示值但仍执行
    • 1) 我更新了第一个答案。 2) HtmlEncode 就足够了。请先在标准 TextBox 控件中测试,不要在自定义服务器控件中测试。
    猜你喜欢
    • 1970-01-01
    • 2012-05-29
    • 2012-03-03
    • 2013-11-15
    相关资源
    最近更新 更多