Thomas Sampson

1 Comment

Getting HTML into a database

Today I found a great function in to convert user inputted string into a format suitable to be held in a database.

The first thing you must do is turn off ValidationRequests. Validation requests are a system .NET has in place to immediately stop the user inputting html into any form . But sometimes you need to allow this. Changing the ValidateRequest attribute of the text entry and submission button didnt work for me , im not sure why, but if the following is included in the webconfig then the user is allowed to submit html through a form (this will compromise security and should be odne with caution).

<pages validaterequest”false”>


At this stage your webapp can now handle html being submitted, but before it can be inserted into a database it must be converted into escape characters.

Here is an example of how to do so, where userinput is plain html entered by the user

string encodedinput=HttpUtility.HtmlEncode(userinput);

this html data can now be inserted into any database using an SQL command. There is no harm using this method on all form submisions, even if they are not likely to contain html. The reason for this is the encode function will also encode illegal charcaters such as double quotes (\”) & % and @ symbols which will be rejected by the database.

When retrieving this encoded html from the database it can easily be dedoded back into regulr html using

string decodedhtml=HttpUtility.HtmlDecode(htmlfromdatabase);

If used carefully, along with SQL injection prevention techniques, this makes for a safe way to store scripts and html in a database.