ASP. NET basics-6. Cookie + 7. Session principles

Source: Internet
Author: User
Tags set cookie
6. cookie7.session principle 7.1 case: Use session to implement verification code.
6. Cookie

The form is page-related and can be obtained only when the browser submits the data to 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-related cookies to the server, which is mandatory.. 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 back to the database, therefore, you can save the information in the cookie and then read and modify it 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..

Case:

Cookie1.aspx

Cookie1.aspx. CS
Protected VoidButton#click (ObjectSender, eventargs e) {response. setcookie (NewHttpcookie ("Color", Textbox1.text ));//$. Cookie can also be used on the client. Set cookie on the server side}

Below is the second page

Cookie read 2. aspx

Cookie read 2. aspx. CS
Protected VoidButton#click (ObjectSender, eventargs e) {label1.text= Request. Cookies ["Color"]. Value ;}

 

 

7. Session Principle

Cookies cannot store too much information. If you want to save a large amount of data, you can save a guid to the cookie, and then create a global dictionary with guid as the key and complex data as the value on the server. The static field has only one copy for different users. Therefore, the static field is used to share data among multiple users.CodeSee remarks ※.

Variable 1. aspx

Variable 1. aspx. CS
 Public  Partial   Class  Variable 1: system. Web. UI. Page {  Protected   Void Page_load ( Object  Sender, eventargs e ){  //  Assign a value to mysessionid for Cookie, guid          If (Request. Cookies [ "  Mysessionid  " ] = Null ){  String Sessionid = Guid. newguid (). tostring (); response. Cookies [  "  Mysessionid  " ]. Value = Sessionid ;}}  //  Set session      Protected   Void Button2_click ( Object  Sender, eventargs e ){  String Sessionid = request. Cookies [ "  Mysessionid  "  ]. Value; idictionary < String , Object > Session = Sessionmgr. getsession (sessionid); Session [  "  Server Data  " ] = 3333  ;}  //  Read session     Protected   Void Button#click ( Object  Sender, eventargs e ){  String Sessionid = request. Cookies [ "  Mysessionid  "  ]. Value; idictionary < String , Object > Session = Sessionmgr. getsession (sessionid); label1.text = Session [ " Server Data  "  ]. Tostring ();}} 
Sessionmgr. CS
 Public   Class  Sessionmgr {  Public  Sessionmgr (){  //          //  Todo: add the constructor logic here  //  }  Private   Static Idictionary <String , Idictionary < String , Object > DATA = New Dictionary < String , Idictionary < String , Object > ();  Public   Static Idictionary < String , Object > Getsession (String  Sessionid ){  If  (Data. containskey (sessionid )){  Return  Data [sessionid];}  Else  {Idictionary < String , Object > Session = New Dictionary < String , Object >(); Data [sessionid] = Session;  Return  Session ;}}} 

ASP. NET has a built-in session mechanism, which overwrites the above example with ASP. netsession. Do not put too many objects into the session,The session has a mechanism for time-out destruction., Post (the server cannot know whether the browser is open or when it is closed), post timing, online time statistics, and request-based judgment on whether it is live.Cookie exists on the client, and session exists on the server. The purpose is the same: to save data related to the current client (the session and cookie can be obtained on any page of the current website ). You cannot put too much data. The stored data is an object..

 

7.1 case: Use session to implement the verification code.

Httphandler must be able to operate sessions and implement the irequiressessionstate Interface. Why does each click value change? It is normal, so every time you click on the page, the page will be refreshed, And you will request the image again from ashx, And the processrequest of ashx will be executed. If a normal website is successfully logged on, it will go to the home page. You will not be able to see the changes, but it will also change once an error is entered.

1. Create YZM. ashx

<% @ Webhandler Language = "  C #  " Class = "  YZM  " %> Using  System;  Using  System. drawing;  Using  System. Web;  Using  System. Web. sessionstate;  // Httphandler uses session to call the irequiressessionstate Interface  Public   Class  YZM: ihttphandler, irequiressessionstate {  Public   Void  Processrequest (httpcontext context) {context. response. contenttype = "  Image/JPEG  "  ;  Using (Bitmap bitmap = New Bitmap ( 50 , 30  )){  Using (Graphics G = Graphics. fromimage (Bitmap )){  //  Random verification code Random ran = New  Random ();  Int Code = ran. Next ( 1 , 9999  ); String Strcode = Code. tostring ();  //  Written to session Httpcontext. Current. session [ "  Code  " ] = Strcode; G. drawstring (strcode,  New Font ( "    " , 12 ), Brushes. wheat, New Pointf ( 0 , 0  ); Bitmap. Save (context. response. outputstream, system. Drawing. imaging. imageformat. JPEG );}}}  Public   Bool  Isreusable {  Get  {  Return   False  ;}}} 

2. Create a page

<Body><FormID= "Form1"Runat= "Server"><Div>

<IMGSRC= "YZM. ashx"/>

         <  ASP: textbox ID  = "Textbox1"  Runat  = "Server"  > </  ASP: textbox  >          <  ASP: button  ID  = "Button1"  Runat  = "Server"  Onclick  = "Button#click"  Text = "Button"   />      </  Div  >      </  Form  >  </  Body  > 

3. Write in the verification code. aspx. CS.

 Protected   Void Button#click ( Object  Sender, eventargs e ){  String YZM = convert. tostring (session [ "  Code  "  ]);  If (YZM = Textbox1.text) {response. Write (  "  Correct  "  );}  Else  {Response. Write (  "  Error  " );}} 

 

Click the image to generate a new verification code. <IMG SRC="YZM. ashx"Onclick="This. src = 'yzm. ashx? AAA = '+ new date ()"/> Every time you click
Generate a new address for the browser to request. It will also be used in Ajax.

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.