Introduction
Most of beginners developers that program in ASP or ASP.NET use Request object.
Usually they use it in the form of Request["Parametr_Name"]
, while not taking into account the fact
that this way of using the object causes a great load on the server performing this task.
Meaning that the server load into memory the whole Request object collection
and has to decide weather to activate
the Request.Form or Request.QueryString methods.
When the site serves a great number of users this can cause a great load on the server.
In this article I'll present a simple way to ease up the server load.
Using the code
In the code below I first check the Request.Form.Count
if it's greater then zero,
then method="post" was used, and I read the given ParamName
, ELSE
I check if Request.QueryString.Count
is greater the zero and only then I decide if to read the parameter.
IF the result is null I turn it into String.Empty
in This way I don't have to check if the value is null and only
then get it's ToString()
method to convert it into string and then check it's value.
public string RequestParam(string ParamName)
{
string Result = String.Empty;
if (Context.Request.Form.Count != 0)
{
Result = Convert.ToString(Context.Request.Form[ParamName]);
}
else if (Context.Request.QueryString.Count != 0)
{
Result = Convert.ToString(Context.Request.QueryString[ParamName]);
}
return (Result==null) ? String.Empty : Result.Trim();
}
So when I use the above code I can do the following:
if (RequestParam("ZipCode").Length < 5)
{
ErrorMesage = "Zip code must contain 5 numeric digits.");
}
In the "Old Way" you could not write
if (Request["ZipCode"].ToString().Length <5)
because if
Request["ZipCode"] == null
it does not have a ToString() method.
Using the code above enables me to use the Request Parameters as a string and saves me writing code to determine if it's null.