Search code examples
asp.netsecurityparametersxsshtml-encode

To HTMLENCODE or not to HTMLENCODE user input on web form (asp.net vb)


I have many params making up an insert form for example:

x.Parameters.AddWithValue("@city", City.Text)

I had a failed xss attack on the site this morning, so I am trying to beef up security measures anyway....

Should I be adding my input params like this?

x.Parameters.AddWithValue("@city", HttpUtility.HtmlEncode(City.Text))

Is there anything else I should consider to avoid attacks?


Solution

  • Don't encode input. Do encode output. At some point in the future, you might decide you want to use the same data to produce PDF or a Word document (or something else), at which point you won't want it to be HTML.

    When you are accepting data, it is just data.

    When you are inserting data into a database, it needs to be converted to make sense for the database.

    When you are inserting data into an HTML document, it needs to be converted to make sense for HTML.

    … and so on.