A large number of querystrings are used in ASP. NET startkit timetracker.
For example:
Http: // localhost/ttwebcsvs_cn/projectlist. aspx? Index = 2
Now let's enter the following address in the IE address. What will happen?
Http: // localhost/ttwebcsvs_cn/projectlist. aspx? Index = a2
Or
Http: // localhost/ttwebcsvs_cn/projectlist. aspx? Index =
Obviously, the index parameter must be an integer, but the parameters in the address we typed do not meet the requirements. An exception occurs.
Is there a way to avoid this situation?
In fact, we can define a base page class.
Public class pagebase: system. Web. UI. Page
Let other aspx pages in the system inherit pagebase.
Write the obtained value in querystring into a method and place it in the base class.
Write three methods in the base class.
< Summary >
/**/ /// Obtain the value of querystring.
/// </Summary>
/// <Param name = "querystringname"> Querystring parameter name </Param>
/// <Param name = "result"> Value of the querystring parameter (string type) </Param>
Protected Void Getquerystringvalue ( String Querystringname, Out String Result)
{
Result = String. empty;
Result = Request. querystring [querystringname];
// No parameter is received. If an exception occurs, go to the error page.
If (Result = Null | Result = "" )
{
Errorpageredirect ();
}
}
/**/ /// <Summary>
/// Obtain the value of querystring.
/// </Summary>
/// <Param name = "querystringname"> Querystring parameter name </Param>
/// <Param name = "result"> Querystring value (INT type) </Param>
Protected Void Getquerystringvalue ( String Querystringname, Out Int Result)
{
String STR;
Getquerystringvalue (querystringname, Out Str );
Result = 0 ;
Try
{
Result=Convert. toint32 (STR );
}
Catch (Overflowexception)
{
//Minvalue less than Int or maxvalue greater than int, exception, go to error page
Errorpageredirect ();
}
Catch (Formatexception)
{
//Non-numeric character, exception, go to error page
Errorpageredirect ();
}
Catch (Argumentexception)
{
//Null reference, exception, go to error page
Errorpageredirect ();
}
}
/**/ /// <Summary>
///When an error occurs, the page turns
/// </Summary>
Protected Void Errorpageredirect ()
{
Response. Redirect ("Errorquerystring. aspx",True);
}
In this way, we only need to call the parent class method on the ASPX page. The method will handle exceptions for us.
For example:
Int ID;
Getquerystringvalue ("", out ID );
If an exception occurs, the method will be processed for us and the page will be directed to errorquerystring. aspx.
We can also record the error information on the errorquerystring. ASPX page, for example, writing the error information to the log or error information table.
The preceding method can only take parameters of the string and INT types.
You can reload the getquerystringvalue method as needed.
I have reloaded it three times in the project and can also take Enumeration type parameters.