stateless HTTP
The requests sent by a viewer are usually responded to by the object implementing the ihttphandler interface. Because the next access may not necessarily be the last response, the object may have been destroyed after the last response, the written class variable value already does not exist, so do not save the state information to the variable.Browser and server usageSocketCommunication, the server will close the currentSocketConnection. In addition, the server will destroy the page object after processing the page.The reason for the application layer is that the communication between the browser and the server compliesHTTPProtocol.
Client status persistence scheme: viewstate, hidden domain, cookies, control status, URL query parameters
Server Status persistence solutions: Session, application, caching, and database)
Cookie
Cookie is a technology that allows the website server to store a small amount of data (about 4 kb) to the client's hard disk or memory and read it out. L when you browse a website, the web server places a very small text file on your hard disk, it can record the information that the website wants to save, such as your user ID, browsed web page, or stay time. When you access the website through a browser again, the browser will automatically send the cookies belonging to the website to the server, and the server will read the cookies to learn your related information, you can make corresponding actions.
For example, you are welcome to the text on the page, or you do not need to enter your ID or password to log on directly. Cookie is not compatible with browsers! (Different browsers do not share cookie file data) simple operations of cookies l server setting COOKIE:
Httpcookie COK = new httpcookie ("uid", "10001"); // ("key", "value ")
COK. expires = datetime. Now. adddays (18); // set the expiration date-18 days later
Context. response. Cookies. Add (COK); // Add to response
The server obtains the cookie sent from the client:
String struname = context. Request. Cookies ["uid"]. value; // obtain the cookie from the request
Notes about cookies
L forms are page-related. Only the data submitted by the browser can be obtained by the server. Sometimes, if you want to access visitor-related information anywhere on the server end, it is inconvenient to save the information to the form, if that is the case, you must always remember to save the information in all Page forms. Cookie is related to the site. In addition to sending form parameters, each request to the server also submits all site cookies to the server. The cookie is also stored on the browser end, And the browser will submit the cookie related to the site to the server each request, and update the cookie returned by the server to the hard disk, therefore, the information can be stored in the cookie and then read and modified on the server. In addition to common HTML data, the server returns a modified cookie. the browser can update the cookie value of the local browser. L even if a file like JPG, JS, and CSS is requested with a cookie, because the server may have session operations, such as checking whether to log. Internet optimization case: The image server and the main site domain name are different, reducing the transmission of cookie traffic. During the interview, the disadvantages of cookie Optimization on websites are the same as those on forms, and too much information cannot be stored. Both the client and server can read the cookie.
SessionSession provides a way to store information in the server memory. It can store any data type, including custom objects.
Sessions on each client are stored independently.
Session objects are used to store user information.
This information is retained throughout the user session. (Before the cookie storing sessionid is lost)
When the user is in the ApplicationProgramWhen you browse from one web page to another, the variables stored in the session object will not be discarded.
Session can only be accessed by the user of the session (because sessionid stores the cache of the visitor's browser as a cookie)
Users cannot access or modify others' sessions
A simple Login Demo using cookies and sessions
A page is deducted from some background websites and slightly changed: for example:
First, let's get the verification code. I found a class to write the verification code from somewhere else, and I used it directly to create a general handler to operate the verification code.CodeAs follows:
Public class creatvalidatecode: ihttphandler, irequiressessionstate // if the general processing program requires a session, implement this interface {public void processrequest (httpcontext context) {context. response. contenttype = "image/JPEG"; common. validatecode = new common. validatecode (); // create a random string for the verification code string STR = validatecode. createvalidatecode (4); // The image validatecode that converts a string into a verification code. createvalidategraphic (STR, context); // when the verification code is handed over to the client, the verification code is placed in session context. session ["validatecode"] = STR ;}
We will write the generated verification code into the session to prevent brute-force cracking by the user, and then make a small function so that the user can click the verification code to switch the verification code, this can be done through javascript. Here I use jquery to switch images. The following address is added with "1" to ensure compatibility with IE.
$ (Function () {$ ("# image1"). Click (function () {// obtain the URL of the current image first. VaR originurl = $ (this ). ATTR ("src"); // set a new address for the SRC address of the current image $ (this ). ATTR ("src", originurl + 1 );});
After the verification code function is completed, we can log on to the logic below. The text box here uses common HTML tags, so we can start to write the login logic.
First, the first request is sent. First, the user name that has been logged on is obtained from the cookie and put in the text box to improve the user experience. When subsequent requests come back, the value is obtained directly from the form, put it in the text box
Protected void page_load (Object sender, eventargs e) {If (! Ispostback) // For the first request, first obtain the user name that has been logged on from the cookie and put it in the text box to improve the user experience {preusername = request. cookies ["username"] = NULL? String. empty: request. cookies ["username"]. value;} else {// when subsequent requests come back, get the value directly from the form and put it in the text box to preusername = request ["txtloginname"];}
First, we must verify the verification code when submitting the request. The specific method is to retrieve whether the verification code of the session is consistent with that of the user request. This step must be completed before other verification.
// Obtain the verification code string sendcode = session ["validatecode"] = NULL? String. Empty: session ["validatecode"]. tostring (); string recievecode = request ["txtcode"]; If (! Sendcode. Equals (recievecode) {JS = "<SCRIPT> alert ('incorrect Verification Code ') </SCRIPT>"; // This method is recommended. Send the JS script return to and from the foreground;
}
The following describes how to verify the user name and password. I wrote a simple script using Layer 3. First, I obtained the user's request and then checked whether the user exists in the database, if the user name exists, it is written into the session and the user name is written into the cookie. I have this step left, and then jump to another page.
String strusername = request ["txtloginname"]; string strpwd = request ["txtpassword"]; // query user information and place it in the session to BLL. hksj_users userinfoservice = new hksj_users (); Model. hksj_users user = userinfoservice. getloginusermodel (strusername, strpwd); If (user = NULL) {// User Logon Failure JS = "<SCRIPT> alert ('user name and password are incorrect ') </SCRIPT> "; // This method is recommended. Send the JS script return to and from the frontend;} // put the user's information into the session to go to session ["loginuser"] = user;
This. response. Redirect ("adminindex. aspx ");
The General login is even completed. Of course, there are still some details that need to be processed.
Thoughts
If we do background management and so on, when we log on, there must be more than one background page. Do we have to query whether sesiion exists every time? If you do this every time, How troublesome it will be!
There is a solution. We can define a basepage class to inherit the page, and then inherit the basepage from the Child page, we can put the verification of the session into the method of the base class. First, we need a basepage class.
Public class basepage: system. web. UI. page // page base class {protected model. hksj_users currentloginuser {Get; set;} // virtual method, which allows subclass override of this method protected virtual void page_preinit (Object sender, eventargs e) {currentloginuser = (model. hksj_users) session ["loginuser"]; If (currentloginuser! = NULL) // if the user has logged on, the session contains the user login information {// This. response. write (currentloginuserinfo. ID + currentloginuserinfo. loginname);} else // {This. response. redirect ("~ /Company website/background management/login. aspx ");}}}
Then we can rewrite the method in the subclass, call the parent class method first, and then write your own unique. The so-called don't repeat yourself, do not repeat yourself.
Cookie and session have made a lot of contributions to maintaining the status. They each have their own characteristics and use cases. We should make good use of them to help us solve some status persistence problems, of course, the viewstate application class can also help us maintain the status. Today we will talk about the two ~ I am a beginner in Asp.net. I am not good at writing in some places. I hope I can learn and make progress together ~