ASP. NET intermediate Learning 1

Source: Internet
Author: User

1. Special path mark "~"

And "/" indicates the root directory of the website (related to the domain name),.../indicates the parent directory,./indicates that the current directory and other Http standard positioning are different, "~", ~ It is a special symbol defined by ASP. NET. It is a recommended method for ASP. NET internal definition. Start from the application root directory.

Programming "~", If it is in the server control, ~ For conversion, if you want to convert html controls or code, you can use static methods in the VirtualPathUtility class to convert virtual paths and full paths, such as VirtualPathUtility. ToAbsolute ("~ /A/B. sapx ")

 

2. Request object

Response. Write (Request. AppRelativeCurrentExecutionFilePath); // obtain the virtual path of the application on the website.

// In this example, the printed virtual path is ~ /Request/RequestTest. aspx

Response. Write ("<br/>" + Request. PhysicalApplicationPath); // obtain the physical path of the current program (path on the server hard disk)

// For example, E: \ learning materials \ ASPNET \ ASP. NET intermediate learning \

Response. Write ("<br/>" + Request. PhysicalPath); // print the physical path of the current page.

// E: \ learning materials \ ASPNET \ ASP. NET intermediate learning \ Request \ RequestTest. aspx

 

Request. UrlReferrer anti-leech is used to determine whether the image Page's UrlReferrer comes from this site. If not, a prompt message and related processing are provided.

 

Response object

Response Buffer output: ASP. by default, the data written by Net to the browser is not immediately output to the browser if no write is performed, but the data is cached, data in the cache area will be sent to the browser at the appropriate time or after the response is completed.

 

Main Member of the Response object:

1. Response. Buffer, Response. BufferOutPut. The two attributes are the same, and Buffer is called BufferOutPut internally. This attribute is used to control whether the response cache is used. The default value is true. (Unless you have special requirements, you do not need to change it)

 

2. Response. Fush () sends the data in the buffer zone to the browser. If you need to output the data from wirte to the browser immediately, this is very suitable. Case: The import of a large volume of data shows the number of data entries being imported. Use Thread. Sleep to simulate the time consumption.

Context. Response. ContentType = "text/html ";

For (int I = 1; I <20; I ++)

{

System. Threading. Thread. Sleep (500 );

Context. Response. Write ("Step 1" + I + "completed <br/> ");

Context. Response. Flush (); // you can see that the data in the browser is printed one by one, instead of printing all the data as before.

}

3. Response. Clear () clears the content in the buffer. In this way, the data in the buffer is deleted directly.

4. Response. ContentEncoding can be used to set and obtain the encoding format of the output stream, but it is not required in general.

5. Response. ContentType the content type of the output stream, for example, html (text/html) or plain text (text/plain) JPEG image (image/JPEG)

 

6. Reponse. The set of Cookies returned to the browser. You can set the cookie through this set. However, we can directly use Response. SetCookie (c); in fact, internal processing helps you Response. Cookies. Add (c );

 

7. Response. OutPutStream: output stream, which is used when outputting non-text files such as images and excel files. For example: bitmap. Save (context. Response. OutputStream, System. Drawing. Imaging. ImageFormat. Jpeg); input an image to the browser.

 

8. Response. End (); terminate the page request and stop executing it. Send the cached data to the browser. When terminating some illegal requests, such as leeching, you can use End () to terminate the request.

Response. Write ("When zookeeper prior to zookeeper does? ? Banned? What is the first access request? Question °! Why? ");

Response. End (); // terminate the request. It will not be executed any more.

Response. Write ("you can't see me! ");

 

9. Response. Redirt ("http://www.rupeng.com"); redirect to the new page, new resources (such as slices), you can navigate outside the site URL.

10. Response. SetCookie (HttpCookie cookie) to update the cookie written to the browser in the output stream. Is a simplified call to Response. Cookies.

11. Response. Write () Outputs content to the browser.

12. Response. WriteFile () Outputs a file to the browser, such as Response. Write ("c/boot. ini ");

 

 

Server Object

Server is an attribute of context and an object of the HttpServerUtility class.

Server. HtmlDecode (), Server. HtmlEncode () html encoding to prevent xss vulnerabilities

Server. UrlEncode () Server. UrlDecode () url encoding. Process hyperlinks.

HttpUtility can also be used to point out these four methods, because it is difficult to obtain the Server Object in some places.

 

Server. Transfer () Internal redirection request, which redirects the user's request to another page for processing, is the internal takeover of the Server, and the browser cannot realize this takeover. Unlike Response. Redirect, the browser is notified to re-access the url address-> the browser accepts commands to access another page. Therefore, the address bar of the browser will not change. Because it is internally taken over, parameters accepted on the redirected pages such as Request and cookies can be accessed, just as these parameters are passed in the past.

Note that Transfer is an internal takeover, so it cannot be redirected to an external website like Redirect.

 

Server. Transfer cannot be directly redirected to ashx; otherwise, an error will be reported "An error occurred while executing the subrequest"

Sometimes you cannot get the HttpContext object. For example, in Global. asax, you can get the Current HttpContext through HttpContext. Current, and then get the Response, Request, Server, and so on.

 

HttpHandler1

1. Dynamic generation of funny images. Writing strings dynamically at a certain position of an image is the same as generating images on the logo website.

 

2. let the browser pop-up box download: If the output is html, txt, jpeg and other types of information, the browser will display it directly. If you want to pop up the Save dialog box, you need to add Header: context. response. contentType = "image/JPEG ";

String filename = HttpUtility. UrlEncode ("Yang fenghui .jpg ");

Context. Response. AddHeader ("Content-Disposition", "attachment; filename =" + filename); // Add the packet header to the output stream

Context. Response. WriteFile ("Yang fenghui .jpg"); // write the file to the browser output stream.

 

Add a message header so that the browser can open the file in the form of attachment (that is, download the attachment)

 

 

The content type ContentType = "application/x-excel" when the application/x-Excel file is downloaded ". Application/octet-stream download all files are OK.

 

Dynamically create an Excel table

Context. Response. ContentType = "application/x-excel ";

String filename = HttpUtility. UrlEncode ("Dynamic Data .xls"); context. Response. AddHeader ("Content-Disposition", "attachment; filename =" + filename );

// Create a new Excel Workbook

HSSFWorkbook hssfworkbook = new HSSFWorkbook ();

// Create a worksheet in an Excel worksheet named Sheet 1

HSSFSheet sheet1 = hssfworkbook. CreateSheet ("bitch ");

// Prepare the expected Worksheet

Sheet1.CreateRow (1). CreateCell (0). SetCellValue ("hello ");

Sheet1.CreateRow (2). CreateCell (0). SetCellValue ("3.14"); sheet1.CreateRow (3). CreateCell (0). SetCellValue ("Are you bitch ?? "); // Write the new Excel table to the browser buffer. Hssfworkbook. Write (context. Response. OutputStream );

 

Gallery exercise: logon handling and brute-force cracking prevention: two fields are added to the user table. One is the lock mark IsLock, and the other is the OpenTime location where you can log on again after a certain period of time.

If the user's password for five consecutive logon attempts is incorrect, set IsLock to 1, and the opening time to the current time plus 30 minutes.

If (user. IsLock = 0) // prevents brute force cracking

{

If (tryCount <5)

{

TryCount ++;

If (user. PassWord = TextBox2.Text. Trim ())

{

TryCount = 0;

Session ["UserId"] = user. Id;

Session ["UserName"] = user. UserName;

Response. Redirect ("PicDownload.html ");

}

Else

{

Label1.Text = "Incorrect password! ";

}

}

Else

{

Adapter. UpdateDataByUserName (1, DateTime. Now. AddMinutes (2), TextBox1.Text. Trim ());

Label1.Text = "the password for five attempts is incorrect. This account has been locked. Please try again in 30 minutes! ";

TryCount = 0;

}

}

Else if (user. IsLock = 1)

{

If (DateTime. Compare (user. OpenTime, DateTime. Now)> 0)

{

Label1.Text = "this account has been locked. Please try again in 30 minutes! ";

}

Else

{

Adapter. UpdateDataByUserName (0, null, TextBox1.Text. Trim ());

TryCount ++;

If (user. PassWord = TextBox2.Text. Trim ())

{

TryCount = 0;

Session ["UserId"] = user. Id;

Session ["UserName"] = user. UserName;

Response. Redirect ("PicDownload.html ");

}

Else

{

Label1.Text = "Incorrect password! ";

}

}

}

In the general handler page, if you need to use the session, you must first implement the IRequiresSessionState interface for the class on this page.

Function: Specify the target Http handler to have read and write access to the session status value. This is just a flag interface and there is no way to do this.

Public class PicDownload: IHttpHandler, IRequiresSessionState

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.