The following example below using the HtmlEncode method.
protected void Button1_Click(object sender, EventArgs e)
{
this.PageLabel.Text = HttpUtility.HtmlEncode(this.UserTextBox.Text);
}
It is best practice to create a helper method to use when writing to the output stream.
This method should make sure that all output strings are passed through the HtmlEncode
method. Performing standard output encoding such as this is one of the few techniques that
cannot be easily bypassed and goes a long way in protecting against input filtering errors.
Earlier in this chapter, you read that developers often want to allow users to supply
formatting instructions, such as bold tags, when submitting content. To do this safely in
.Net, use the HtmlEncode method to encode the data and then use the string replacement
functions to replace the encoded versions of allowed tags with the real versions.
For example replace >b< with
. Using a whitelist approach after performing
encoding provides a much higher level of assurance that attackers will not be able to
supply tags that may compromise an application??™s security.
126 Hacking Exposed Web 2.0
A final note on output encoding to remember is that using the HtmlEncode method
does not make input safe for insertion into client-side script blocks such as JavaScript.
Pages:
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247