This tutorial will show you how to manage your SQL data connections and data access methods to improve security issues against SQL Injection Attacks. C#.

Web Applications that allow or require user input to function are susceptible to certain attacks by malicious users. If not properly protected, user input can cause problems because users may be able to interject their own SQL commands into the application and cause havoc with your database(s) – modifying or even deleting sensitive or crucial data.

In this tutorial, we will look at ways we can prevent the user from doing this. First, let us start with a simple Web Form using Visual Studio .NET 2008 and a sample database. We will use a table named tblNames, and have an id column and a name column. The id will be Primary Key, and identity specification. We will then add some sample data to the database. If you have your own database and web application to use, please feel free.

We will be using the following connection string in the Web.config:

We will use a Repeater control to display data from our database, and then allow additions to the database with the use of two text boxes:

The first step is to validate the user input on the front-end. We can do this using the built-in ASP.NET Validation controls. Regular Expression validators are great for making sure a user uses the correct format for entry, for such things as a US phone number, Zip code, or Social Security Number. However, when using validators, it is also important to use the Page.IsValid method on the code-behind. This will ensure that the validators work even when JavaScript is disabled in the client’s browser.

The next step is to validate the input on the code-behind. Notice below that we first check that the page is valid on button click. If the field validators’ expressions are met, then the page is valid. Otherwise, the page is invalid and the code will not execute.

The next statement we carry out another test to see if the names field consists of alphanumeric characters – if it does, we execute the Add method. However, if the name field consists of illegal characters, an exception will occur and the database will not be accessed.

In order to use RegEx, we add the following assembly references:

Finally, in our data access method, we use Stored Procedures and parameters as an added measure of security. In these two methods, we show two different ways of using the parameters. In the second method, where we add data, we add a database type to the parameter. This is referred to as a type-safe stored procedure. If the type is not matched, the stored procedure will not execute.

To access a SQL database and use the Web Configuration Manager, we add the following assemblies to our class:

Download Source Files