4

Given the following URL:

domain.com/page.aspx?id=123

How can I sanitize that query string value when it is used on a Databound Control such as a repeaters SqlDataSource?

<asp:SqlDataSource ID="projectDataSource" runat="server" 
    ConnectionString="MyConnectionStrings" 
    SelectCommand="select foo from bar">
    <SelectParameters>
        <asp:QueryStringParameter 
            DefaultValue="0" 
            Name="idfromqs" 
            QueryStringField="id" 
            Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>

Such that ?id=asdf does not result in an error?

These similar questions have good answers, but none of them seem to quite match my problem

Note: This is an internal application that is limited to a small block of local ip address. I'm less worried about malicious sql injection and more about preventing less savvy users from seeming nasty error messages.

Community
  • 1
  • 1
Michael Jasper
  • 7,962
  • 4
  • 40
  • 60

2 Answers2

2

You could use the Selecting event of the SQLDataSource where you can check the querysting value. This event fires before the Select Method is called.

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    SqlDataSource1.SelectParameters.Clear(); //Clear existing parameters
    // based on your check, you can pass the default value
    SqlDataSource1.SelectParameters["idfromqs"].DefaultValue = "Set Value here";

}
Off The Gold
  • 1,228
  • 15
  • 28
Muhammad Akhtar
  • 51,913
  • 37
  • 138
  • 191
  • So, If I understand correctly: the sqldatasource has an event that is triggered BEFORE the query is executed on the database, and in this event I can check if the value is correct or not before proceeding? – Michael Jasper Aug 09 '11 at 17:38
1

Just take the type off. A querystring is a already string, unless you convert it explicitly to something else (like an int32). If there's some reason to convert it to an int32, you can do that later int he code where it's easier to apply logic to.

<asp:QueryStringParameter 
   DefaultValue="0" 
   Name="idfromqs" 
   QueryStringField="id" />
Chains
  • 12,541
  • 8
  • 45
  • 62
  • 1
    If ID was int, and you compared it to a string (WHERE id = 'asdf'), yeah, you'd just get nothing -- no error either. As long as you're using parameters, no injection issues either. Of course, how the id variable in the querystring got a value that was not numeric might be worth looking into though. – Chains Aug 09 '11 at 17:47
  • Hmm... This did not work as I had hoped: Removing the type from the parameter just shifted the error down the road a little. As opposed to just returning nothing and having and empty control, I received a "Conversion failed when converting the nvarchar value 'asdf' to data type int" Error from the database. – Michael Jasper Aug 09 '11 at 17:50
  • That *sounds* like sql-server talking... What are you doing with the variable down the line? – Chains Aug 09 '11 at 17:52