1. Review
A) WebForm front and Back page (aspx, aspx.cs) files are compiled into classes when they are accessed, and foreground classes inherit from the background class
b) When accessed, the server creates a "Foreground page class" object as the object that handles browser requests
c) How is the foreground class object combined with the method of the background class to generate HTML code for the entire page? When the---is requested, the page control object tree is generated (the control tree is created when the PR method is executed), and the control tree is responsible for organizing the contents of the entire page (_buildcontroltree ()---Building the control tree method)
d) Inheritance Relationship: Front page class, background page class, page-> TemplateControl, Control (contains ControlCollection collection, used to save child controls)
e) for ASP. The dynamic page aspx or ASHX is run as an object of the class when requested by the browser, rather than just reading the contents of the file as if it were a static page HTML or JPG
f) The Page_Load () method is called each time the page is requested in WebForm, and the PR method in type Ashx
2. Request other Members
L request.urlreferrer request from the source, can judge from Baidu search of which keyword, anti-download/Picture hotlinking, can forge (such as thunder). Global anti-theft chain with Globals.asax
L hotlinking: the contents of their own servers, stolen by other servers, displayed on someone else's web page (that is, access to the content of a server page, via hyperlinks can directly access the content of B server)
L Solutions:
1) the server automatically according to the picture name and the current time of the request to generate a key (ciphertext), after receiving the request message, the server calculates the time of the picture request, and then take this time and the current server time to compare, if the time is more than 1 minutes, do not return the picture content
2) use public key: Add a public key to the picture data and parse it at the request
L request.userhostaddress Get the IP address of the visitor
L Request.Cookies Get browser -side cookies sent by browsers
Read Cookie value: request.cookies["Mysessionid"]
Write cookie value: RESPONSE.COOKIES.ADD (HttpCookie cookie)
L Request.mappath (Virtulpath) converts the virtual path to a physical path on the disk,
Request.mappath ("~/a/b.aspx") will get D:\2008\WebSites\WebSite4\a\b.aspx
When a user clicks on a hyperlink on the List.aspx page, an attribute is added to the browser-generated request message: (the page path representing the current click Hyperlink): Referer:http://localhost:1256/webform/list.aspx
Add:
1, Request.apprelativecurrentexecutionfilepath, gets the virtual path of the current execution request relative to the application root, starting with ~, such as "~/handler.ashx",
2, Request.physicalapplicationpath, get the physical path of the current application, such as d:\ My Documents \visual Studio 2008\websites\website4\
3, Request.PhysicalPath, gets the physical path of the current request, such as d:\ My Documents \visual Studio 2008\WEBSITES\WEBSITE4\HANDLER.ASHX
4, Request.rawurl get the original request URL, Request.url get the requested URL, the difference is related to URL rewriting problems
5, Request.UserLanguages to obtain the language that the visitor browser supports, can through this realizes to the different language person to display the different language the page.
3. Other members of response
Buffered output of the response:
In order to improve the performance of the server, ASP. NET write to the browser when the default does not immediately output to the browser every write once, but will cache the data, to the appropriate time or the end of the response will be in the buffer to send the data together to the browser.
Response main members of the object:
1, Response.Buffer, Response.bufferoutput: Whether the response cache is used, the default is true. After reflector, the two properties are found to be the same, and the inside buffer is called BufferOutput.
2, Response. Flush (): The data in the response buffer is immediately output to the browser. Case: Import of large quantities of data, showing that the data is being imported, using Thread.Sleep to simulate time-consuming.
3, Response. Clear (): Empties the data in the buffer so that no data sent to the browser in the buffer will be sent to the browser.
4, response.contentencoding the output stream encoding.
response.contentencoding = System.Text.Encoding.Unicode
5. Response.ContentTypResponse.ContentEncodinge the content type of the output stream, such as HTML (text/html) or plain text (text/plain) or JPEG (image/ JPEG).
6. Response.Cookies A collection of cookies returned to the browser, which can be used to set cookies
7, Response.outputstream output stream, in the output of images, Excel files and other non-textual content to use it
8. Response.End () Terminates the response, sends the data in the previous cache to the browser, the code afterend () stops executing, and the flush () method is called in the End method. Can be used to terminate some illegal requests, such as hotlinking, etc.
9, Response.Redirect (URL) redirect the browser to a new URL (off-site website or site URL).
Response.Redirect ("http://www.rupeng.com"), Response.Redirect ("a.htm").
The redirect process goes through the server notifying the browser "Please revisit URL this url" and the browser is instructed to access the new URL. Use HttpWatch to view HTTP messages for the entire response process. With redirect because it is the browser to re-visit the new URL, so in the address bar can see the changes in the URL. This will be used later to prevent prompting for "retry" when the browser is refreshed.
10, Response.setcookie (HttpCookie cookie), to the output stream to update the cookie written to the browser, if there is no update exists on the increase. is a simplified call to response.cookies.
11, Response.Write () output content to the browser.
4. Server (HttpServerUtility)
L Server is a property of context objects, an object (instance) of the HttpServerUtility class that provides access to methods and properties on the server
Common methods for L server objects
1) MapPath (string path) method to obtain the physical path of the file
2) Execute method and transfer method, execute script of another page
A) Execute (string path), access the redirected page, place its contents in the response buffer, execute the code after the redirect statement, and finally output
b) Transfer (string path), terminates execution of the current page and begins a new page of the specified path. ( internal Redirect request, executes another page on the server side, and returns the result of the execution to the browser)
Because it is an internal takeover, the redirected page is accessible to the parameters that are accepted by the request, cookie, and other source pages, just as these parameters are passed to him, and redirect is not, because it is for the browser to access.
Attention:
I. The code after the transfer method does not run
II. Transfer is an internal takeover and therefore cannot be redirected to an external website like redirect.
III. Cannot redirect directly to ashx, otherwise error "execution of sub-request Errors"
3) HTMLEncode method and HtmlDecode method
A) HtmlEncode (string s) method, HTML-encodes the string and returns the encoded string
b) HtmlDecode (string s) method to decode the HTML-encoded string and return the decoded string
4) UrlEncode method and UrlDecode method, URL encoding and decoding
A) the UrlEncode (string s) method, URL-encodes the string, and returns the encoded string. For handling Chinese issues in hyperlinks
b) The UrlDecode (string s) method decodes the URL-encoded string and returns the decoded string.
Attention:
HtmlDecode (), HtmlEncode (), UrlEncode (), UrlDecode () are a proxy call to the corresponding method in the HttpUtility class. It is recommended to always use httputility because it is difficult to get the server object in some places, and the existence of the server is reserved for the previous ASP programmer's habits. Recommended for Httputility.htmlencode.
L Sometimes can't get HttpContext objects, such as in Global.asax (back), can get the current HttpContext through HttpContext.Current, and then get response/request/ Server, etc.
5, stateless HTTP (that is , the server does not remember the last time to give the browser what )
The root cause of a stateless state is:
the browser and server use socket communication, and the server closes the current socket connection after the request results are returned to the browser. And the server destroys the Page object after the page finishes processing.
the reason for application is that communication between the browser and the server adheres to the HTTP protocol.
Reasons for not saving state information to class variables:
A visitor requests a response from an object that implements the IHttpHandler interface, because the next access is not necessarily the last time the object responds, the last response object may have been destroyed, and the value of the class variable that was written already does not exist.
impact on the site : If the user entered some information, when the jump to the next page, the data is lost, no longer get those data.
Workaround (record status information somewhere):
A. Server-side
B. browser-side
C. form elements, such as: Hidden Fields <input type= "hidden"/> (http messages)
L Why do aspx and generic handlers have to implement the IHttpHandler interface? Because the server does not know what kind of class the user will write, what method is written in the class, so Microsoft stipulates that any class that can be accessed by an external request must implement the IHttpHandler interface; Once the user-written class implements this interface, is bound to include the ProcessRequest method in the interface, then the server can be called uniformly.
code example:
Http://www.oumind.com/index.aspx
Object o= .... The server reflects the object of the user-requested page class based on the path requested by the user (index_aspx, this class must have implemented the IHttpHandler interface).
IHttpHandler h = (IHttpHandler) o;
H.processrequest ();
6, ASP. NET status (information) retention scheme 11:31
1) The client's status-preserving scheme:
ViewState, hidden fields (Hidden field), Cookies, control state, URL query parameters (QueryString)
Essentially 3 kinds: hidden field/cookies/querystring (url?name=1)
2) service-side status-preserving program:
Session, Application (Object), Caching (cache), database
Common State ( information) retention mode ( emphasis) :
L ViewState:
ASP. aspx page-specific, page-level, a way to save data that is used separately by the client in a hidden field on the page;
How to save data (key-value pairs):
viewstate["MyKey"]= "MyData"; equivalent to Viewstate.add ("MyKey", "MyData");
How to read data:
String MyData;
if (viewstate["MyKey"]!=null)
{
Mydata= (String) viewstate["MyKey"];
}
The values of the server-side controls are automatically saved in ViewState, and ViewState cannot store all data types, only supported: String, Integer, Boolean, Array, ArrayList, Hashtable
L Use premise: there must be a runat=server form on the page
When the server receives a user request for a page, it automatically looks in the request message for the hidden domain containing the __viewstate and, if there is one, decodes the median value and adds it to the ViewState property of the page.
When the server is output, it will automatically add the value in ViewState to the hidden field called __viewstate in the form.
L viewstate for the same page to interact with the server multiple times without shutting down
L cross-page submissions are not loaded into the ViewState property of the page by the target page __viewstate
Disadvantages :
1) Increase the flow of the website
2) Reduced access speed
3) confidential data placed on the form will have security issues such as data spoofing.
Hidden fields are still present, except that the properties and values of the server-side controls are not saved: Enableviewstate=false (disabled)
ViewState main Save: Property values for server-side controls, user-defined ViewState key-value pairs 14:30
1) The ViewState property of the page actually gets the value in a hidden field named _viewstate that the browser submitted.
2) in the Page class object, when the implementation of the PR method, the control tree was created, and then by the execution of the LoadState method, the name of the request message is __viewstate, and then anti-Base64 number, deserialized, and eventually reverted to a set, Then it belongs to the programmer itself (11::56 also contains the data and status of server-side running space??? The key value added to the ViewState is restored to the ViewState property of the Page object. The Page_Load method is then executed.
Attention:
L Cookies:
HTTP a way under the agreement, by this way, the server or script can maintain state information on the client;
is a way for the client to save the data that the client uses separately;
Just like your medical history, the hospital takes you home directly;
L Session: associated with the process (now refers to the session within the process).
A way to save data that is used separately by the client on the server side;
Like a bank account, where money exists in a bank, you take a bank card (SessionId) home;
L Application:
A way to save shared data on the server side;
Like the bank's single-person public health room, who can go in, but one at a time, in the lock door, come out and then open the lock;
7. the viewstate in Aspx (emphasis, frequent test)
View the generated source code, ASP. NET puts all the hidden content in a hidden field named __viewstate, using a serialization algorithm to put all the hidden content into a string. Click on the tool to view ViewState content using Viewstatedecoder, and find out that the changes are actually put in viewstate. A container that stores non-form fields, non-value values.
Disable ViewState Method of :
1) Disable single control: Set Property EnableViewState= "false",
Disabling viewstate after the TextBox version is not affected, the div version is affected because the value of input does not depend on viewstate.
2) Disable the entire page, plus enableviewstate= "false" in the ASPX page instruction area. Intranet system, the background of the Internet can enjoy the use of viewstate.
Answer ViewState principle : Say the input version (TextBox) is different from the increment and div version (Label). (Perfect!!! --When certain properties of some controls are not part of the submission scope of the browser form, the FW will add these attributes to the ViewState save.
WebForm's IsPostBack (callback, BOOL type) relies on viewstate. As long as the browser submits a request message containing the __viewstate key, ASP. NET will set the page's IsPostBack property to True. (whether submitted via the address bar or by a hyperlink or a click of a button, the server will set IsPostBack to true as long as the __viewstate key is present)
8. Cookies (Cookie)-Medical records
A cookie is a technique that allows a Web server to store a small amount of data (around 4kb ) on a client 's hard disk or memory and read it out.
When you browse a website, a very small text file is placed on your hard drive by the Web server, which can record your user ID, the page you visited, or the time of your stay and other information that the site wants you to save. When you visit the website again through a browser, the browser will automatically send the cookie that belongs to the website to the server, the server can make the corresponding action by reading the cookie and knowing your relevant information.
such as on the page display welcome your banner, or let you do not have to enter the ID, password directly login and so on.
When a browser accesses a site, only the cookie belonging to the current site is sent to the server. (based on domain name)
L Cookies are stored on the client side , not compatible with the browser!
L It is best to encrypt the content that will be saved on the server side, why?
The location on the hard drive is closely related to the operating system and browser used.
There are two ways to save cookies in a browser:
In memory of the browser;
On the hard drive of the computer on which the browser resides.
L DateTime Expires property to set the expiration time for the cookie object:
Cook. Expires = DateTime.Now.AddMinutes (5);//set to expire after COOK5 minutes
Development scenario: Often used to log in and save the user recently viewed Items
Cookies the Expires property is not readable. ( can be set only when writing to the browser)
Cookies the Operation
L Server Settings Cookie:
HttpCookie cok = new HttpCookie ("UId", "10001");//("Key", "value")
Cok. Expires = DateTime.Now.AddDays (18);//Set expiration date-18 days after now
Context. RESPONSE.COOKIES.ADD (COK); Add to Response
The server obtains the cookie from the client:
String Struname=context. request.cookies["UId"]. value;//obtaining a cookie from the request
How does the cookie principle---specific?
1) Normal GET request no cookie
2) The server sets cookie information to the browser by responding to the Set-cookie in the message header
3) The browser passes the cookie information stored by the browser by requesting a cookie in the message header
The server writes out a cookie to the browser that actually generates the response line in the response message:
* SET-COOKIE:UINFO2=123; Expires=mon, 06-jun-2011 06:48:47 GMT; path=/
* The browser will automatically generate a cookie file on the client hard disk after reading this response line, named:
* Cookie:[email protected]/, note that after the @ localhoust/, is actually issued this Cookie website domain name;
* The next time the browser accesses this domain name, the content of the cookie file with the suffix localhoust/will be automatically sent to the server.
1) Cookies. Path (generates a cookie for the specified folder)
2) cookies. Domain (domains/domain) www.oumind.com book.oumind.com
3) Relationship between Response.Cookies and Request.Cookies-a common part
4) Where the cookie is stored in the browser's hard drive:
C:\Documents and Settings\ login account name \cookies
Can be opened automatically by start-run-cookies.
Add:
The total size allowed by different browser cookies (including name, value, and equal sign ):
Firefox and Safari cookies---------up to 4,097 bytes
Opera------------up to 4,096 bytes
IE----------up to 4,095 bytes
The browser allows each domain name to contain cookies Number:
Microsoft noted that IE8 added a cookie limit of 50 per domain name, but IE7 also seems to allow 50 cookies per domain name.
Firefox has a limit of 50 cookies per domain name.
Opera has a limit of 30 cookies per domain name.
Safari/webkit seems to have no cookie restrictions. However, if there are many cookies, the header size will exceed the server's processing limit, which can cause errors to occur.
Note: "Each domain cookie limit is 20" will no longer be correct!
when a lot of cookies is set, how the browser responds.
In addition to Safari (you can set all cookies, no matter how many), there are two ways:
Least recently Used (LRU) method: When the cookie has reached the limit, automatically kicks apart the oldest cookie to give some space to the latest cookie. leastrecentlyused InternetExplorer and Opera Use this method.
Firefox is unique: Although the last set of cookies is always retained, it seems to randomly determine which cookies are retained. There seems to be no plan (recommended: Do not exceed the cookie limit in Firefox).
9. Session (HttpSessionState )
Session provides a way to store information in server memory. It can store various data types including custom objects. Development scenario: Often used to save logged-in users ID
Use :
Assignment: session["UName"]= "SXL";
Value: String strname=session["UName"]. ToString ();
Destroy (Cancel, exit): Session.Abandon ();//Destroy Session object on server side
Session.clear ();//clearing the key-value pair in the session object of the server
A Session object is created on the server side of a key-value pair for Uid=strid, which is stored in the session pool on the server side and the ID number of the session object is obtained from the session pool.
Session Common Properties, Methods :
SessionId: Unique user session identifier
Timeout: User timeout (in minutes), default is 20 minutes
Count: Number of items in the session-state collection
Abandon method: For displaying end sessions
Attention:
1) This information will be retained throughout the user session. But when the session expires or terminates, the server clears the Session object
2) Session object is used to store information about the user. Each client session is stored independently, and the user cannot access or modify the session of another person. Session can only be accessed by the user of the conversation (because the SessionID is saved in the browser's cache by a cookie)
3) When the user browses from one page to another in the application, the variables stored in the Session object are not discarded.
16:40
Cookie and session preservation mechanism
In the HttpApplication request pipeline 9th event, according to the browser SessionID automatically read SessionID corresponding session object from the session pool, and assigned to the current Page object session properties
If the browser disables cookies, the server can also be saved through SessionID in the URL to complete sessionid between the browser and the server side (need to set the sessionstate node in the configuration file cookieless= " AutoDetect ")
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319 under the Aspnet_isapi.dll
ASP. NET Notes