Do not drag controls asp.net--Discovery Cookie and session (2)

Source: Internet
Author: User
Tags httpcontext setcookie

Next to the previous blog, we will explain the server-side saving data mechanism-session

We know that cookies are stored on the client side, so that the data there is an unsafe, in addition to the problem is not able to store a large amount of data, our previous blog also left a problem is that the client can tamper with the data, the equivalent of the patient's hand is retained in the medical records are likely to be tampered with by the user (under normal circumstances , the user will not tamper, so much danger, doctor misdiagnosis how to do? haha

In addition, the doctor will give each patient a number, and then save a number, so that when the patient comes to identify the patient's identity according to the number, of course, the user will be able to guess the number of other people's numbers, then how to do?

  1. Implement "Cookie on the server"-session

We need a "server-side Cookie": 1. The doctor needs a private ledger to record the correspondence between the patient's number and identity; 2. In order to prevent the patient from guessing the number of people based on the number assigned to him, a "hard to guess" coding mechanism is needed.

How to prevent the patient from guessing the number of others: random numbers can, but not best, because the generation of random numbers may occur duplicates, what is the best? Using GUIDs (explained in the previous blog) to generate unique numbers based on network card numbers and so on, it is guaranteed that the generated numbers are unique worldwide.

So where does the Doctor's private ledger exist, and we know it's not safe in the patient's hands? The answer is that there can be static variables inside the static manager session.

Then let's practice.

    ? Sample Demo

Here we still use the nvelocity template-driven mechanism to demonstrate, or to encapsulate the template in the Commonhelper class. No longer write code here, the previous has been written, the details of reference: Link:http://blog.csdn.net/u010955843/article/details/43117097

after establishing the 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 Summary 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 a doctor assigned user number Sessionmgr.jizhang (ID, username); Write in the ledger when landing//the patient number assigned by the Doctor is written into the medical history context. Response.setcookie (New HttpCookie ("Zhangbenid", id.                    ToString ())); Context.                Response.Redirect ("Test1.ashx");            }}} public bool IsReusable {get {return false; }}}}</strong></span>

Create a generic handler Test1 to read the cookie and output it

<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>//Test1 Summary description///</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 {ret            Urn false; }}}}</strong></span>

Create a new class to write methods that define how to save, get 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 {//Dictionary is a type of key-value pair that defines the name of a GUID that is always present when the. NET Framework is running, which can be saved on the server side (the Doctor's ledger        ), and will not disappear because the HTTP request disappears private static dictionary<guid, string> Zhangben = new Dictionary<guid, string> ();        Assign the ID of the ledger to public static void Jizhang (Guid ID, string value) {Zhangben[id] = value; }//whether to journal public static bool Isjizhang (Guid ID) {return zhangben.        Keys.contains (ID); }//Add static here because HTTP is stateless, but generate static, which is saved during the entire framework run, can save the entire value on the server side public static string Get (Guid ID        ) {return zhangben[id]; }}}</strong></span> 

Create template engine render template HTML page for login.html (Create a folder templates,html write under folder, synchronize with location in template engine)

<span style= "Font-family:microsoft yahei;font-size:14px;" ><strong><! DOCTYPE html>
      ? Message parsing

The first time to enter the program is not a cookie, the display interface such as

at this point we fill in the login username and password (set up before themselves, because at this time I just do an example, did not establish a connection with the database, so wrote a password. The else code in the login program is executed, and a cookie is written into the message such as:

The information in post is the information we enter

after processing in the TEST1.ASHX, the corresponding cookie value will be judged before the output

The so-called self-realization of the session mechanism, the data stored on the server side, is to store an ID; There is a limit to the size of the file placed by the client, but the server side does not have this limit, the memory is very large; when we open a new address bar in the same browser again and input the time still display the output cookie, indicating that this is saved on the server side, and can be shared, However, in different browsers will be turned to the login interface, the explanation is not cross-browser, because IE and Firefox mechanism is not the same.

2. ASP. NET built-in session mechanism

ASP. NET has built-in the session mechanism, the above example with Asp.netsession rewrite. Ordinary HttpHandler to be able to operate the session, implement the IRequiresSessionState interface. Read-write pages have to implement this interface, Login2 is written to the session, and test is read session.

    ? Example Commonhelper and encapsulation get, save SessionID the same way, and the template HTML is the same, the difference is the program login.ashx and TEST1.ASHX code changes.

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 description///</summary>//ASP. NET built-in session must introduce namespace System.Web.SessionState, also to implement 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") {//server-side provided index context.                    session["yonghuming"] = Username; Context.                Response.Redirect ("Test1.ashx");            }}} public bool IsReusable {get {return false; }}}}</strong></span>

test1.ashx Read 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>////TEST1////</summary>////////////Irequiressessionst Ate public class Test1:ihttphandler, irequiressessionstate {public void ProcessRequest (HttpContext context ) {context.            Response.ContentType = "text/html"; if (context. Session = = null) {context.            Response.Redirect ("Login.ashx"); The else {//session can store any character-type 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

The first time to enter the program is no session, the display interface such as

at this point we fill in the login username and password (set up before themselves, because at this time I just do an example, did not establish a connection with the database, so wrote a password. The else code in the login program is executed at this time and is written to the session with messages such as:

The information in post is the information we enter

after processing in the TEST1.ASHX, the corresponding cookie value will be judged before the output

Compare the "server-side cookies" we realized before, what do we find?

  3. How much does SessionID know?

comparing the two we can find that the session is actually dependent on the cookie, which generates a value internally, is to generate an ID to the client, it is dependent on the cookie, but with the help of a cookie mechanism allows us to store data on the server side, This is the principle of the session; The session relies on cookies and relies on cookies to help it save an ID.

The number ID that the doctor wrote on the medical record is SessionID. Comparing our own implementation of "server-side cookies", we better understand the implementation mechanism of our session.

4. The destruction of the session

An Internet that automatically destroys when a session does not interact with the server for a certain period of time, and ASP. NET provides such a mechanism.

Like a doctor's book, when a patient does not come for a long time, the doctor will destroy it for a long time, so there is an assistant to record the patient's medical records, a person to see the disease, and always record the patient's last visit to the doctor, remove the long-term patients, so as to reduce the pressure and memory on the server side, Improve the performance of the operation.

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 periodically, which is why a period of inactivity, the system will automatically exit.

When you do not log in for a long time, when you log in again, the reason for the system reminder is that the session automatic destruction mechanism. The default time is automatically destroyed after 30 minutes. Therefore, we understand the principle of the session, so that we make good use of it.

 5. Summary

Do not know what to say is not clear, the cache in our programming program has a very important application, learn it easy for us to better use it, interested in their own try it.




Do not drag controls asp.net--Discovery Cookie and session (2)

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.