0
public ActionResult PostMessage(string message)
{
    MessageController mc = new MessageController();
    mc.postMessage(message);
}

What can I do here to prevent SQL injection in this string? This is the only input the user is given on the entire page. I am familiar with the some PHP techniques, but how would I protect myself in c#?

Thanks!

edit:

connection.Open();
SqlCommand command = new SqlCommand("[dbo].[tblMessages_Insert]", connection);
command.CommandType = CommandType.StoredProcedure;

// params
SqlParameter messageText = new SqlParameter("@messageText", SqlDbType.VarChar);
messageText.Value = message;

// add params
command.Parameters.Add(messageText);

rows = command.ExecuteNonQuery();
adrianbanks
  • 81,306
  • 22
  • 176
  • 206
Scott
  • 4,066
  • 10
  • 38
  • 54
  • 2
    I would imagine it depends on what database API you're using! – Oliver Charlesworth Apr 05 '11 at 23:47
  • in .net - system.data.sqlclient – Scott Apr 05 '11 at 23:47
  • 1
    What are you using to store data in your database? If you are using DbCommands and parameters correctly or an ORM, you should be protected automatically. I would be more concerned about CSS issues if you are taking that user message and writing it back out to HTML at some point later in your app. – Eric Petroelje Apr 05 '11 at 23:48
  • 1
    @Scott - let's see that database access code. Without seeing that I couldn't really say for certain.. – Eric Petroelje Apr 05 '11 at 23:49
  • possible duplicate of [How do I convert a string into safe SQL String?](http://stackoverflow.com/questions/5528972/how-do-i-convert-a-string-into-safe-sql-string) – Michael Stum Apr 05 '11 at 23:55

1 Answers1

3

It seems to me that you're already protecting against injection; you're using parameters.

Giovanni Galbo
  • 12,963
  • 13
  • 59
  • 78
  • 1
    Parameterized stored procedures provide some inherent protection against injection. However if you're building and executing dynamic sql inside the procedure, look out :) – womp Apr 05 '11 at 23:55
  • yes I know... but based on the name of his stored proc it seemed unlikely that anything dynamic was going on :) – Giovanni Galbo Apr 05 '11 at 23:57