Do not drag the control ASP. NET -- discover cookies and sessions (2), asp. netcookies
Next we will go to the previous blog to explain how the server stores data-session
We know that cookies are stored on the client, so there is an insecure data. In addition, there is a problem that it cannot store a large amount of data, another problem left over from our previous blog is that the client can tamper with the data, which is equivalent to the fact that the patient's medical records are retained by the user (in general, the user will not tamper with the data, what should I do if my doctor misdiagnoses this risk? Haha)
In addition, the doctor prepares a number for each patient and saves a number to identify the patient when the patient arrives, of course, the user can guess his/her own number from others' numbers. What should I do?
1. Implement the "server cookie"-session by yourself
We need a "server-side Cookie": 1. The doctor needs a private ledger to record the correspondence between patient numbers and identities; 2. To prevent the patient from guessing the number of the person before and after the number assigned to him, a "difficult to guess" encoding mechanism is required.
How to prevent patients from guessing others' numbers: random numbers are acceptable, but not the best, because random numbers may be generated repeatedly. What is the best? Using Guid (described in the previous blog) to generate a unique ID based on the ID of the NIC. It ensures that the generated ID is globally unique.
So where does the doctor's private ledger exist? Do we know that it is not safe in the hands of patients? The answer is that there can be static variables, that is, static Manager session.
Let's try it out.
Ø demo
Here we still use the Nvelocity template driver mechanism for demonstration, or encapsulate the template in the commonHelper class. No code is written here. The previous code has been written. For details, refer to: link:Http://blog.csdn.net/u010955843/article/details/43117097
Then create a general handler Login
<Span style = "font-family: Microsoft YaHei; font-size: 14px;"> <strong> using System; using System. collections. generic; using System. linq; using System. web; namespace session {/// <summary> // Login abstract description /// </summary> public class Login: IHttpHandler {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/html"; // context. response. write ("Hello World"); string login = context. request ["Login"]; if (string. isNullOrEmpty (login) {string html = commonHelper. renderHtml ("Login.html", null); context. response. write (html);} else {string username = context. request ["UserName"]; string password = context. request ["password"]; if (password = "123456") {// context. response. setCookie (new HttpCookie ("UserName", username); Guid id = Guid. newGuid (); // generate the user ID sessionMgr assigned by the doctor. jizhang (id, username); // write the patient number assigned by the doctor into the patient history context at login. response. setCookie (new HttpCookie ("zhangbenId", id. toString (); context. response. redirect ("Test1.ashx") ;}} public bool IsReusable {get {return false ;}}</strong> </span>
Create a general processing program Test1 to read and output the cookie.
<Span style = "font-family: Microsoft YaHei; font-size: 14px;"> <strong> using System; using System. collections. generic; using System. linq; using System. web; namespace session {// <summary> // summary of Test1 /// </summary> public class Test1: IHttpHandler {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/html"; // context. response. write ("Hello World"); HttpCookie cookie = context. request. cookies ["zhangbenId"]; if (cookie = null) {context. response. redirect ("Login. ashx ");} else {Guid id = new Guid (cookie. value); if (sessionMgr. isJizhang (id) {string value = sessionMgr. get (id); context. response. write (value);} else {context. response. redirect ("Login. ashx ") ;}}public bool IsReusable {get {return false ;}}</strong> </span>
Create a new class to write some methods and define the methods for saving and obtaining cookieid.
<Span style = "font-family: Microsoft YaHei; font-size: 14px;"> <strong> using System; using System. collections. generic; using System. linq; using System. web; namespace session {public class sessionMgr {// The dictionary is a key-Value Pair form that defines a Guid name, static in. net framework always exists during running, so that it can be saved on the server (doctor's account book); it does not disappear because of the disappearance of http requests. private static Dictionary <Guid, string> zhangben = new Dictionary <Guid, string> (); // assign the public static void Jizhang (Guid id, string value) to the account id) {zhangben [id] = value;} // whether to keep the account public static bool IsJizhang (Guid id) {return zhangben. keys. contains (id) ;}// add static here because http is stateless, but static is generated, which can be saved during the entire framework runtime, the server can save the entire public static string Get (Guid id) {return zhangben [id] ;}}</strong> </span>
Set the html page of the template engine to login.html (create a folder templates, write html under the folder, and synchronize it with the location in the template engine)
<Span style = "font-family: Microsoft YaHei; font-size: 14px;"> <strong> <! DOCTYPE html> Ø Message Parsing
There is no cookie when you enter the program for the first time. The interface is shown as follows:
At this point, we enter the login user name and password (I have set it myself, because I just made an example and did not establish a connection with the database, so I wrote a password .) In this case, the else code in the Login program is executed and written into the cookie. The message is as follows:
The information in Post is the information we entered.
And then process it in Test1.ashx. The corresponding cookie value will be determined before output.
The so-called self-implemented session mechanism saves data to the server, that is, stores an id;The size of files placed on the client is limited, but the server does not have this limit, and the memory is large; when we open a new address bar in the same browser and input it, the output cookie is still displayed, indicating that the cookie is saved on the server and can be shared, however, in different browsers, the logon interface will be switched, indicating that it cannot be used across browsers, because the mechanism of ie is different from that of Firefox.
2. Asp. NET built-in session mechanism
ASP. Net has a built-in Session mechanism, which overwrites the above example with ASP. Netsession. The normal HttpHandler must be able to operate sessions and implement the IRequiresSessionState interface. To read and write pages, you have to implement this interface. login2 is the write session, while test is the read session.
Ø example
CommonHelper and encapsulation methods for obtaining and saving SessionId are the same, and the template Html is the same. The difference is that the Code changes in the program Login. ashx and Test1.ashx.
Login. ashx
<Span style = "font-family: Microsoft YaHei; font-size: 14px;"> <strong> using System; using System. collections. generic; using System. linq; using System. web; using System. web. sessionState; namespace ASP. NETSession {// <summary> /// Login summary /// </summary> // ASP. NET built-in session must introduce the namespace System. web. sessionState; it is also used to implement the IRequiresSessionState interface public class Login: IHttpHandler, IRequiresSessionState {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/html"; // context. response. write ("Hello World"); string login = context. request ["Login"]; if (string. isNullOrEmpty (login) {string html = commonHelper. renderHtml ("Login.html", null); context. response. write (html);} else {string username = context. request ["UserName"]; string password = context. request ["password"]; if (password = "123456") {// The index context provided by the server. session ["yonghuming"] = username; context. response. redirect ("Test1.ashx") ;}} public bool IsReusable {get {return false ;}}</strong> </span>
Test1.ashx reads SessionId
<Span style = "font-family: Microsoft YaHei; font-size: 14px;"> <strong> using System; using System. collections. generic; using System. linq; using System. web; using System. web. sessionState; namespace ASP. NETSession {/// <summary> /// summary of Test1 /// </summary> // Similarly, the IRequiresSessionState public class Test1 interface must be implemented for reading cookies: IHttpHandler, IRequiresSessionState {public void ProcessRequest (HttpContext context) {context. response. contentType = "text/html"; if (context. session = null) {context. response. redirect ("Login. ashx ");} else {// Session can store any struct string yonghuming = (string) context. session ["yonghuming"]; if (string. isNullOrEmpty (yonghuming) {context. response. redirect ("Login. ashx ");} else {context. response. write (yonghuming) ;}}public bool IsReusable {get {return false ;}}}</strong> </span>
Ø Message Parsing
There is no session when you enter the program for the first time. The interface is shown as follows:
At this point, we enter the login user name and password (I have set it myself, because I just made an example and did not establish a connection with the database, so I wrote a password .) In this case, the else code in the Login program is executed and written into the session. The message is as follows:
The information in Post is the information we entered.
And then process it in Test1.ashx. The corresponding cookie value will be determined before output.
What did we find by comparing our self-implemented "server-side cookies?
3. What is SessionId?
By comparing the two, we can find that the Session actually depends on the cookie, which internally generates a value, generating an id to the client, which is dependent on the cookie, the cookie mechanism allows us to store data on the server. This is the principle of session. session depends on cookie and cookie to store an id.
It is equivalent to the number id written by the doctor in the medical history. It is sessionid. Compared with our own "server-side cookies", we can better understand the implementation mechanism of our Session.
4. Session destruction
When a session does not interact with the server for a certain period of time, it is automatically destroyed. asp.net provides such a mechanism.
Like a doctor's ledger, when a patient does not arrive for a long time, the doctor will destroy the patient for a long time. In this way, an assistant will record the patient's medical records, when a person sees a doctor, he always records the patient's last visit and deletes the patient who has never been there for a long time. This reduces the pressure and memory on the server and improves the running efficiency.
The Session has an automatic destruction mechanism. If the browser does not interact with the server for a period of time, the Session will be destroyed on a regular basis, which is why the Session is not operated for a period of time, the system automatically exits.
When you do not log on for a long time, the system prompts you to log on again because of the automatic destruction mechanism of the session. The default time is 30 minutes. Therefore, we understand the principle of session to make good use of it.
5. Summary
I don't know if it is clear. cache has an important application in programming. Learn it well so that we can use it better. Try it if you are interested.