Verification Date Field
Verify that the date field is of the correct type. in most cases, you also need to verify their scope, such as whether they are future or past time. if you use the Server Control to capture a Date input value and want the value to be within a specific range, you can use the range verification control (RangeValidator) set the allowed type to Date. this control allows you to specify a special time period by setting the start time. you can use the CustomValidator verification control to verify whether a time is in the future or in the past.
To use the CustomValidator control to verify a date, you must set the ControlToValidate and ErrorMessage attributes, and specify a custom authentication logic method in the OnServerValidate event. The following is the sample code.
<% @ Page Language = "C #" %>
<Script runat = "server">
Void ValidateDateInFuture (object source, ServerValidateEventArgs args)
{
DateTime dt;
//
Check for valid date and that date is in the future
If (DateTime. TryParse (args. Value, out dt) = false) |
(Dt <= DateTime. Today ))
{
Args. IsValid = false;
}
}
</Script>
<Html>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: Label ID = "Label1" Runat = "server"
Text = "Future Date:"> </asp: Label>
<Asp: TextBox ID = "futureDatetxt" Runat = "server"> </asp: TextBox>
<Asp: CustomValidator
ID = "CustomValidator1" Runat = "server"
ErrorMessage = "Invalid date. Enter a date in the future ."
ControlToValidate = "futureDatetxt"
OnServerValidate = "ValidateDateInFuture">
</Asp: CustomValidator>
<Br/>
<Asp: Button ID = "submitBtn" Runat = "server" Text = "Submit"/>
</Div>
</Form>
</Body>
</Html>
Note that the method DateTime. TryParse used in the above Code is a new method provided by ASP. NET2.0.
Filter free text fields
Filter input. You need to prevent insecure input from being treated as code. for example, if your program prevents users from reading data from the shared database, you must first filter the data so that it is not dangerous to output the data. use HttpUtility. the HtmlEncode method first encodes the input value.
Limited HTML code input allowed
Add the following field ValidateRequest = "false" to the @ Page element to disable ASP. NET Request verification.
Use HtmlEncode to encode the input string
Use the StringBuilder object to call its Replace method to Replace the HTML in the character
The following code provides an example of this method. this page sets ValidateRequest = "fasle" to disable ASP.. NET Request verification. its HTML encoding allows <B> and <I> to display simple text formats.
<% @ Page Language = "C #" ValidateRequest = "false" %>
<Script runat = "server">
Void submitBtn_Click (object sender, EventArgs e)
{
//
Encode the string input
StringBuilder sb = new StringBuilder (
HttpUtility. HtmlEncode (htmlInputTxt. Text ));
//
Selectively allow and <I>
Sb. Replace ("& lt; B & gt;", "<B> ");
Sb. Replace ("& lt;/B & gt ;","");
Sb. Replace ("& lt; I & gt;", "<I> ");
Sb. Replace ("& lt;/I & gt ;","");
Response. Write (sb. ToString ());
}
</Script>
<Html>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: TextBox ID = "htmlInputTxt" Runat = "server"
TextMode = "MultiLine" Width = "318px"
Height = "168px"> </asp: TextBox>
<Asp: Button ID = "submitBtn" Runat = "server"
Text = "Submit" OnClick = "submitBtn_Click"/>
</Div>
</Form>
</Body>
</Html>
Verify the query string value
Verify the length, range, format, and type of the query string. Generally, you use a combined regular expression to complete the following tasks:
Constraint input value
Set clear range check conditions
Specify the input type and convert it to ASP. the following code example shows how to use the Regex class to verify the name string passed by the query string.
Void Page_Load (object sender, EventArgs e)
{
If (! System. Text. RegularExpressions. Regex. IsMatch (
Request. QueryString ["Name"], @ "^ [a-zA-Z '. s] {1, 40} $ "))
Response. Write ("Invalid name parameter ");
Else
Response. Write ("Name is" + Request. QueryString ["Name"]);
}
Verify Cookie value
Values stored in cookies like query strings are easily modified by users. The length, range, format, and type of these values are also verified.
Verify the file and URL
If your program allows you to enter a file name, file address, or file storage path, you need to verify that their format is correct and that it points to a valid location based on the actual situation of your program. if this step fails, your program may be incorrectly requested to access the file.
Verify file path
To prevent your program from being used by users to access files, and to prevent users from writing code input files or file paths. For example:
If you accept the input file name, use the System. IO. Path. GetFileName method to obtain the full name of the file.
If you have to accept the input file Path, use System. IO. Path. GetFullPath to obtain the complete file Path.
Use MapPath to prevent cross-application ing
If you use the MapPath method to map a provided virtual directory to a physical directory on the server, use Request. an overloaded version of The MapPath method with bool parameters to prevent cross-application ing. the following is a sample code for this technology:
Try
{
String mappedPath = Request. MapPath (inputPath. Text,
Request. ApplicationPath, false );
}
Catch (HttpException)
{
//
Cross-application mapping attempted
}
The final false parameter will prevent cross-application ing. This means that you are not allowed to use the syntax like "..." to provide an invalid path not in your specified virtual directory.
If you use the server Control, you can use Control. MapPathSecure to obtain the actual directory address corresponding to the virtual directory.
The Control. MapPathSecure method throws an HttpException when accessing an unauthorized file. For more information, see Control. MapPathSecure In the. NET Framework document.
Use the code access security mechanism to restrict file input and output
The administrator can set the program to "medium" to restrict the program's ability to read and write files to its virtual directory .. NET code security mechanism can ensure that the program does not have any file access rights outside its virtual directory.
To set the application's trust to "medium", you can add the following to the Web. config or Machine. config file:
<Trust level = "Medium"/>
Verify URL
You can use a regular expression like the following to perform URL feature matching.
^ (? : Http | https | ftp): // [a-zA-Z0-9.-] + (? : D {1, 5 })? (? : [A-Za-z0-9.;: @ & =+ $ ,? /] | % U [0-9A-Fa-f] {4} | % [0-9A-Fa-f] {2}) * $
This only restricts the input format and does not verify whether it is within the acceptable range of the application. you should verify whether it is valid in the context of your program. for example, does your application communicate with the server you specified?
Step 3. encode Insecure code
If you enter text into a webpage, use HttpUtility. HtmlEncode to encode it. If the text comes from user input, database, or a local file, make sure that this is always the case.
Similarly, if the URL you write contains insecure characters because they come from user input content, databases, and so on, use the HttpUtility. UrlEncode Method for encoding.
To prevent the stored data from being corrupted by the Pre-encoding, make sure to encode the data as follows when displaying them.
Use HtmlEncode to encode insecure output
HtmlEncode replaces HTML tags with special string containing texts to represent these symbols, and the browser does not interpret them as HTML tags. for example. "<" replaced with & lt; "(colon) with & quot; these labels are displayed as harmless text.
<% @ Page Language = "C #" ValidateRequest = "false" %>
<Script runat = "server">
Void submitBtn_Click (object sender, EventArgs e)
{
Response. Write (HttpUtility. HtmlEncode (inputTxt. Text ));
}
</Script>
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: TextBox ID = "inputTxt" Runat = "server"
TextMode = "MultiLine" Width = "382px" Height = "152px">
</Asp: TextBox>
<Asp: Button ID = "submitBtn" Runat = "server" Text = "Submit"
OnClick = "submitBtn_Click"/>
</Div>