GibboK
GibboK

Reputation: 73908

Encode/Decode a TextBox

I use Asp.Net 4, C# and MS SQL.

For my website I use MS default solution for preventing Cross-Site Scripting.

I'm also used to ENCODE all User's Inputs in my logic so that this data can be stored ENCODED in my Data Base.

At the moment I'm using a GridView to do some basic CRUD operation but I'm facing a problem.

My questions: - How to do it? - Because I have many TextBox in many pages in my application, how to centralize this behavior?

Thanks guys for your help!

Upvotes: 4

Views: 2833

Answers (1)

blowdart
blowdart

Reputation: 56490

Firstly I would say that you should never encode before storing in a database. You encode at the point of output - before you put it in a text box, or a grid or wherever.

This has a few advantages;

  1. You're format agnostic - you can take your data and put it as HTML, XML, JSON or whatever because you haven't locked yourself to a single format when storing.
  2. It makes search easier, if you're searching those fields.
  3. If there is a bug in the Encode function you're using you may end up storing unsafe values. By encoding at the point of output you could replace your encoder with a non-buggy one, or one using a blacklist rather than a whitelist without having to go through all your data, pulling it out, decoding it and re-encoding it.

In the case of textbox the actual encoding depends on the type of textbox - a single line text box is attribute encoded, a multiline text box is HTML encoded, and using the text property of the asp.net textbox control encodes for you, using the correct method.

By storing "raw" HTML you remove the need to decode because the controls are encoding automatically for you, there is nothing for you to centralise.

Upvotes: 3

Related Questions