0

was using HttpUtility.UrlEncode() to prevent SQL injection on where clauses. However some of the text being input has spaces and replacing them with %20 will stop the query. Is there a better alternative?

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
CerIs
  • 527
  • 3
  • 6
  • 14

2 Answers2

1

Use parameters in your database queries rather than concatenating input. Job done. If that sounds like a lot of work - consider tools like dapper that make it easy:

string name = ...
int regionId = ...
var customers = connection.Query<Customer>(
    "select * from Customers where Name = @name and RegionId = @regionId",
    new { name, regionId }).AsList();
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

To prevent SQL Injection it is preferred to use SQL Parameters. When working with parameters SQL ensures that the parameters in the query are never executed.

Never construct queries by concatenating strings. Especially when it is input that is untrusted (Received from a user)!

In your case using c# you can take a look here: http://csharp-station.com/Tutorial/AdoDotNet/Lesson06

Nitzo
  • 79
  • 6
  • Hi, how would you do that in a linq/API based system? IE Results.WhereLike("missionCountry", "%" + prefixText + "%"); ??? – CerIs Aug 31 '16 at 15:24
  • `ObjectQuery contactQuery = context.Contacts .Where("it.LastName = @ln AND it.FirstName = @fn", new ObjectParameter("ln", lastName), new ObjectParameter("fn", firstName));` (In this case ln and fn are the parameters) – Nitzo Aug 31 '16 at 15:38