Validation

F

Franck Diastein

Hi,

How can I securely validate the Id's I receive with QueryString ?

This is what I do now:

if ( Request.QueryString["ID"].ToString() != string.Empty ) {
m_TaskID = int.Parse(Request.QueryString["ID"].ToString() );
mystuff();
}

With this I only validate that I'm receiving something, but hao can I
check the value received is int ?

TIA
 
W

William F. Robertson, Jr.

The parse will fail if it isn't an int, so you could wrap it in a try catch
block to determine if it is an int.

string id = Request.QueryString["ID"];

if ( id != null && id.Length != 0 )
{
try
{
int m_TaskID = Int32.Parse( id );
mystuff(); //this will only execute when the parse happens
correctly.
}
catch( FormatException )
{
//it is not an int
}
}

Commentary:
Request.Querystring[] might return null, so you can not safely call
..ToString() on it. Also, it returns a string already, so there is no need
to call .ToString() on it.

Also I never check a string to String.Empty. It is much faster to check the
property .Length to 0.

Now in version 2.0, there will be a method call .TryParse() that will return
true or false for you and save you the exception trap, but that isn't slated
this summer 05

HTH,

bill
 
G

Guest

Yes - A bit awkward to use try/catch for regular logic flow but thats the way
its got to be done in .net 1.x

2.0 has int32.TryParse which will retrun a bool if it is a int

William F. Robertson said:
The parse will fail if it isn't an int, so you could wrap it in a try catch
block to determine if it is an int.

string id = Request.QueryString["ID"];

if ( id != null && id.Length != 0 )
{
try
{
int m_TaskID = Int32.Parse( id );
mystuff(); //this will only execute when the parse happens
correctly.
}
catch( FormatException )
{
//it is not an int
}
}

Commentary:
Request.Querystring[] might return null, so you can not safely call
..ToString() on it. Also, it returns a string already, so there is no need
to call .ToString() on it.

Also I never check a string to String.Empty. It is much faster to check the
property .Length to 0.

Now in version 2.0, there will be a method call .TryParse() that will return
true or false for you and save you the exception trap, but that isn't slated
this summer 05

HTH,

bill

Franck Diastein said:
Hi,

How can I securely validate the Id's I receive with QueryString ?

This is what I do now:

if ( Request.QueryString["ID"].ToString() != string.Empty ) {
m_TaskID = int.Parse(Request.QueryString["ID"].ToString() );
mystuff();
}

With this I only validate that I'm receiving something, but hao can I
check the value received is int ?

TIA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top