Session explanation, ASP. NET core knowledge (8), sessionasp.net

Source: Internet
Author: User

Session explanation, ASP. NET core knowledge (8), sessionasp.net
Introduction Session

1.Function

Cookie exists on the client, and Session exists on the server for the same purpose: save data related to the current client (any page on the current website can get the Session ).

In my sister-in-law Cookie details in this blog post, Black Rabbit finally talked about Cookie defects. Simply put, it cannot store important data. How to store the status of important data? Cookie sister Session gives you a good answer.

2.Doctor's account book

 

A "server-side Cookie" is required: A doctor needs a private ledger to record the correspondence between patient numbers and identities. Because the ID card cannot be fake, the information cannot be fake. (If the ID card cannot be fake, the ID card can uniquely identify the user.) The core information is stored on the server and the client cannot be tampered. This is the general principle of Session.

 

3.IRequiresSessionState 

Cookies cannot store confidential data. Use the Session mechanism that has been built in ASP. Net. Normal HttpHandler must be able to operate sessions and implement the IRequiresSessionState interface. This interface does not have any method to mark the interface, because Session processing will slightly reduce system performance, therefore, HttpHandler does not process sessions by default. If the asp.net engine sees that ashx implements the IRequiresSessionState, it will help us deal with it.

4.Self-destruction device

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. That is why the system automatically exits after a period of time.

Of course, sessions can also be manually destroyed, such as the secure exit function. It is needed. Context. Session. Abandon (); // destroy the Session

5. Self-destruction countdown

In the web. config system. configure the timeout of the sessionState node in the web node. The unit is minute and the default value is 20. (This is just a suggestion. The Session may be invalidated when the server is 10 minutes)

How to Use Session in. NET

1.Session can store any type

1 // the Cookie value is String2 // The Session value can be almost any type of 3 context. response. contentType = "text/html"; 4 context. session ["test1"] = "HelloWorld"; 5 context. session ["test2"] = 888;

 

2. logon case

This case is intended to demonstrate the use of the Session, but it is definitely not a real login. Writing in the project like this will definitely be killed...

1) Login page

1 // a good little habit. Set the Session name to a constant field. 2 // you can directly reference this field in the future to avoid writing errors. 3 public const string LOGINUSERNAME = "LoginUserName"; 4 public void ProcessRequest (HttpContext context) 5 {6 context. response. contentType = "text/html"; 7 string username = context. request ["username"]; 8 string password = context. request ["password"]; 9 if (password = "123") 10 {11 context. session [LOGINUSERNAME] = username; 12 context. response. redirect ("Main. ashx "); 13} 14 else15 {16 context. response. write ("Incorrect password"); 17} 18}

2) pages to be viewed only after Logon

1 public void ProcessRequest (HttpContext context) 2 {3 context. response. contentType = "text/html"; 4 string username = (string) context. session [Login1.LOGINUSERNAME]; 5 if (username = null) 6 {7 context. response. redirect ("login.html"); 8} 9 else if (username = "admin") 10 {11 context. response. write ("Wow, good old! "); 12} 13 else14 {15 context. Response. Write (" Current logon username "+ username +" no permission to view "); 16} 17}

3.Verification Code 

Regarding the verification code, the Session can record the verification code value. The Black Rabbit gave a detailed description in the article "how to generate the verification code in detail.

Session Principle

1. Check the http packet

Through http packets, we found that there is a ASP. NET_SessionId = a4dsx... character in the Cookie. What does this mean? Yes, she is a Session.

2. Session is the Cookie in the server.

Under normal circumstances, the Session is stored in the server's content, and the browser stores this Cookie with SessionId content. The memory of the server with Session is like a bank, and the corresponding browser Cookie is like a bank card. SessionId is the bank card number. The browser does not store any important information. Only one "key" can open the bank. This is the principle of Session.

3. Use cookies to simulate a Session 

1 public class MySession 2 {3 // MySessionId is the Cookie name of the memory card number. The value in Cookie is the real SessionId. 4 private const string MYSESSIONID = "MySessionId"; 5 private HttpContext context; 6 private string sessionId; 7 public MySession (HttpContext context) 8 {9 this. context = context; 10 HttpCookie cookie = context. request. cookies [MYSESSIONID]; 11 if (cookie = null) 12 {13 CreateSession (); 14} 15 else16 {17 this. sessionId = cookie. value; 18} 19} 20 21 private void CreateSession () 22 {23 // use Guid to simulate a Session Id24 Guid guid = Guid. newGuid (); 25 this. sessionId = guid. toString (); 26 HttpCookie cookie = new HttpCookie (MYSESSIONID); 27 cookie. value = sessionId; 28 context. response. setCookie (cookie); 29} 30 31 public void SetValue (string name, string value) 32 {33 // save path on the server side. 34 string fullpath = context. Server. MapPath ("~ /MySession/"+ sessionId); 35 Dictionary <string, string> dict; 36 if (File. exists (fullpath) // if the File Exists, deserialize the previous data to 37 {38 using (Stream stream = File. openRead (fullpath) 39 {40 BinaryFormatter bf = new BinaryFormatter (); 41 dict = (Dictionary <string, string>) bf. deserialize (stream); 42} 43} 44 else45 {46 dict = new Dictionary <string, string> (); // if it does not exist, create an empty dictionary 47} 48 dict [name] = value; 49 // dict. add (name, Value); // set the value to 50 using (Stream stream = File. openWrite (fullpath) // reserialize and save dict to the file 51 {52 BinaryFormatter bf = new BinaryFormatter (); 53 bf. serialize (stream, dict); 54} 55} 56 57 public string GetValue (string name) 58 {59 string fullpath = context. server. mapPath ("~ /MySession/"+ sessionId); 60 Dictionary <string, string> dict; 61 if (File. exists (fullpath) // if the File Exists, deserialize the previous data to 62 {63 using (Stream stream = File. openRead (fullpath) 64 {65 BinaryFormatter bf = new BinaryFormatter (); 66 dict = (Dictionary <string, string>) bf. deserialize (stream); 67} 68} 69 else70 {71 dict = new Dictionary <string, string> (); // if it does not exist, create an empty dictionary 72} 73 if (dict. containsKey (name) 74 {75 return dict [name]; 76} 77 else78 {79 return null; 80} 81} 82}
View Code

1) In this example, a Cookie named MySessionId is used to store SessionId. SessionId = context. Request. Cookies [MYSESSIONID]. value. SessionId is the name of the Session data stored on the server.

2) A Dictionary object is stored on the server side through serialization and deserialization.

3) The SessionId value is generated by the Guid. I don't know how to name ASP. NET. I just want to use GUID as an identifier.

4) In short, this case demonstrates such a schematic. This schematic diagram is basically consistent with the Seesion mechanism.

Out-of-process Session

1.Out-of-process Session?

As I said, in general, sessions are stored in the server's memory. This method will lead to a certain amount of performance loss. An out-of-process Session is used to store the Session from the memory.

2.Configuration method for saving Session in SQLServer

1. Run the aspnet_regsql.exe file under the netframeworkinstallation directory to create related databases, tables, and stored procedures. For example:

C: \ Windows \ Microsoft. NET \ Framework \ v4.0.30319> aspnet_regsql.exe-ssadd-sstype p-S 127.0.0.1-U sa-P 123456

 

-Sstype p indicates that the database name is fixed to ASPState,-S (uppercase) indicates the database server address, and-U and-P indicate the database username and password respectively,

For more information about parameters, see http://blog.csdn.net/yuanzhuohang/article/details/6758304.

2) modify the web. config sessionState node configuration: <sessionState mode = "SQLServer" timeout = "20" sqlConnectionString = "server = .; uid = sa; password = 123456; "> </sessionState>

Cookie in this article

Cookie details

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.