0
votes

I have a web application using aspx pages. First, I wanted to use Server.HtmlEncode(value) whhen displaying the value in a LabelledTextBox

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);
        }
    }
}

The value <script>alert("hello")</script> was displayed but the script was executed.

Afterward, I wanted to try another solution which was to handle the exception

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

to stay on the same page containing the form and displaying an error message on the top with a generic message like "Please be sure that all input does not contain characters like '<' or '>'"

Solution 1 : What am I doing wrong ?

Solution 2 : How can I handle this exception and stay on the same page with the filled in form

General : Which solution is the best ?

Thx !

1

1 Answers

0
votes

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

You see this server exception because user enters HTML tag (such as < >) inside Textbox control, and submits the form.

There is nothing you can prevent it at server-side. However, you can create a client-side validation script, and warn the user or strip out the tags.

For example,

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

The value alert("hello") was displayed but the script was executed

This is opposite of above scenario. Server renders Script tag to browser.

In order to prevent it, as you said you want to encode the string using HttpServerUtility.HtmlEncode before rending it.

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