How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings

Most scripting exploits occur when users can get executable code (or script) into your application. By default, ASP.NET provides request validation, which raises an error if a form post contains any HTML.

You can help protect against script exploits in the following ways:

  • Perform parameter validation on form variables, query-string variables, and cookie values. This validation should include two types of verification: verification that the variables can be converted to the expected type (for example, convert to an integer, convert to date-time, and so on), and verification of expected ranges or formatting. For example, a form post variable that is intended to be an integer should be checked with the System.Int32.TryParse method to verify the variable really is an integer. Furthermore, the resulting integer should be checked to verify the value falls within an expected range of values.

  • Apply HTML encoding to string output when writing values back out to the response. This helps ensure that any user-supplied string input will be rendered as static text in the browsers instead of executable script code or interpreted HTML elements.

HTML encoding converts HTML elements using HTML–reserved characters so that they are displayed rather than executed.

To apply HTML encoding to a string

  • Before displaying strings, call the HtmlEncode method. HTML elements are converted into string representations that the browser will display rather than interpret as HTML.

    The following example illustrates HTML encoding. In the first instance, the user input is encoded before being displayed. In the second instance, data from a database is encoded before being displayed.

    NoteNote

    This example will only work if you disable request validation in the page by adding the @ Page attribute ValidateRequest="false". It is not recommended that you disable request validation in a production application, so make sure that you enable request validation again after viewing this example.

    Visual Basic
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _
    As System.EventArgs) Handles Button1.Click
    Label1.Text = Server.HtmlEncode(TextBox1.Text)
    Label2.Text = _
    Server.HtmlEncode(dsCustomers.Customers(0).CompanyName)
    End Sub

    private void Button1_Click(object sender, System.EventArgs e)
    {
    Label1.Text = Server.HtmlEncode(TextBox1.Text);
    Label2.Text =
    Server.HtmlEncode(dsCustomers1.Customers[0].CompanyName);
    }

See Also

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值