Get and post in HTTP, ViewState principle

Source: Internet
Author: User
Tags setcookie

HTTP is the model of the request, the response, the server does not come to read the browser Web page, only can get the data submitted by the client.
When the user clicks Submit, the server knows "submit back" (PostBack)

Get vs. Post


Set the method property of the form to specify how the form is submitted, and get (the default value) is passed by URL value, the amount of data passed is limited
Post-pass form values are hidden in the HTTP message, the URL is not visible, there will be a browser prompt to resubmit the form of the problem, get no
Get mode URL data format, server file name followed by "? ", because the client may submit multiple key-value pairs to the server,
The key-value pair is split with "&", and if the URL has Chinese characters, special symbols, etc., the URL needs to be encoded
The form field will be submitted to the server only if name is set.

Web page only the Value property of the Input,textarea,select that has the name set will be submitted to the server
Non-form elements cannot pass values to the server's
such as: To set the value of the Div, directly is not possible, can be implemented by hiding the field, the value of the hidden field is set to the same as the Div content
Then when the user submits the information, the server obtains the value of the hidden field and replaces the value with all the values of the page

If the From form method property is specified as GET, then the action=1.ashx?a=123 parameter is deleted
If specified as post, the arguments in the action are submitted to the server to

ViewState principle (for solutions to the above problem)

The value of the label version is stored in the ViewState, and the textbox version does not exist, because the textbox is input and is submitted to the server, and no hidden fields are required.
Used for ASP. div Text self-increment (also increment label width, note the unit of width)
Label1.Text = (Convert.ToInt32 (label1.text) +1). ToString ();
Label1.width = new Unit (Label1.Width.Value + 10);
To view the generated source code, ASP. NET puts all the hidden content in a hidden field named __viewstate, using serialization
The algorithm puts all the hidden content into a string and clicks on the tool using Viewstatedecoder to view the ViewState
Content, and found that these changes were actually put in the ViewState

How to disable ViewState: Add Enableviewstate= "false" to the top page tab, disable ViewState after
The textbox version is not affected, and the Div version is affected because the value of input does not depend on ViewState (a single control can be disabled)
Disabling ViewState does not completely remove the viewstate, there will be a small piece of code, if you want to be in the page completely viewstate
Then there can be no runat=server form in the page, if the button and other service-side controls are not placed in the Runat=server form
, then it's not necessary.

When answering the ViewState principle, say: Input version (TEXTBOX) is different from increment and div version (Label)

---------ViewState Use:

     Assign this to ViewState in the background          . viewstate["key"] = "004";          This. Viewstate.add ("Key2");     Call ViewState    Label1.Text = this. viewstate["Key"]. ToString ();

As long as there is a runat=server form will produce _viewstate and so on, so remove the form runat=server, so that in addition to a few controls such as repeater, server control can not be used, only use HTML tags.
This is why it is said that "high-demand Internet projects do not have server-side controls"

Stateless HTTP

1.HTTP protocol is stateless, will not remember the last and the page "What happened", if you want to know the last state,
One way to do this is to save the state information to the page form before the browser response is finished, and the next page will send a request to the server
With these status messages so that the server can restore the last state based on these state information.
2. The disadvantage of saving state information in hidden fields: increase the traffic of the website, reduce the speed of access, and put the confidential data into the form there will be data spoofing and other security issues

Cause: HTTP is the TCP protocol used, in order to reduce the consumption of the server, when the server responds to the client, then immediately segment off, so no state

Asp. NET saves state in the following ways:

Application Current application (all users use one application)
Session Current Sessions (one session per user)
Cookies are stored on the client's
ViewState for the current page (one viewstate per page)

First, Application Object

Application is global, save and operate on the server side, anyone can access

Save with Object
This. application["T1"] = TextBox1.Text;
Application.Lock ();//Lock
Application.UnLock ();//unlock

Can be in the Global.asax of the page access, click to do some statistics

Second, the use of cookies

A cookie exists on the client
Cookies are site-related, and each time a request is made to the server, in addition to the form parameters are sent, all site-related
Cookies are submitted to the server, are mandatory, cookies are stored on the browser side, and the browser will be on every request
The cookie that is associated with this site is submitted to the server and the cookie returned by the service is updated back to the database so that the information can be
Save the cookie and then read and modify it on the server side.
The server returns data in addition to normal HTML data, the modified cookie is returned, and the browser updates the value of the cookie to the local
The browser's cookie can be

Set up:

Response.setcookie (New HttpCookie ("Color", TextBox1.Text));

Or

RESPONSE.COOKIES.ADD (New HttpCookie ("Size", "22"));

Read:

Lable1.text = request.cookies["Color"]. Value;

Extended use:

HttpCookie H1 = new HttpCookie ("Color", TextBox1.Text);    Create a Cookie object H1. Expires = DateTime.Now.AddHours (1);    Set expiration time, only in datetime format h1.httponly = true;    Sets whether the client can access script Response.setcookie (H1);    Set Cookieresponse.appendcookie ();    Append cookies

The disadvantage of cookies, like forms, cannot store too much information.

Website Optimization case:
Web site image server to be different from the main site domain name, reduce the transfer of cookie traffic
Note: Images, css,js and other static files are all separate requests.

If a website has more than one map, there is a local cookie on that website,
Then, when accessing, request HTML to pass a cookie once, request each picture to pass a cookie again, this is wasted.
If the domain name of the image server is not the same as the master station, the cookie will not be transmitted when the image is downloaded.
Because cookies are not cross-domain!!

Third, the session principle

Session is stored on the server side, the object type is stored
private int i = 0; Every time a request comes, a new instance of the class "variable" that implements the IHttpHandler interface
Processing, the GC is out of use, so the last value will not be maintained, so it will not be self-increasing
private static int j = 0; Static is not instantiated, and all visitors access the same instance of J.
The last value is still saved, so it will increment itself
Cookies cannot store too much information, and if you want to save a large amount of data, you can save a GUID to a cookie, and then create a GUID key in the server, and the complex data as the value Global dictionary,static field for different users only one copy,

The

therefore uses static to implement multi-user shared data, the code is as follows:

public class sessionmgr//session Admin page {private static idictionary<string,idictionary<string, Object>&gt ;    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;        Add value for data, SessionID to Key,session as value return session; }}} protected void Page_Load (object sender, EventArgs e)//Load Event {if (request.cookies["Mysessionid"] = = NULL)//Determine if there is a mysessionid, no increase {string sessionId = Guid.NewGuid ().            ToString ();        Response.setcookie (New HttpCookie ("Mysessionid", sessionId));    }} protected void Btus_click (object sender, EventArgs e)//Set Session Click event{String sessionId = request.cookies["Mysessionid"].        Value;        Idictionary<string, object> session = Sessionmgr.getsession (SESSIONID);  session["Data on the server"] = DateTime.Now; Add key value} protected void Butd_click (object sender, EventArgs e)//Read Session Click event {string sessionId = Reque St. cookies["Mysessionid"].        Value;        Idictionary<string, object> session = Sessionmgr.getsession (SESSIONID); Butd.    Text = convert.tostring (session["Data on the service side"]); }

ASP. NET has built-in session mechanism, the above example with Asp.netsession rewrite,
Note: Do not put too many objects into the session,session there will be a mechanism for timeout destruction
You can see that the session mechanism is not specified by the HTTP protocol, is the implementation of ASP, and now php,jsp and so on most of the service-side technology
I realized the session, the principle is similar
If the user disables the Session, you can add properties to the <system.web> inside the web.conf to save Seesionid to the URL, <sessionstate cookieless= "UseUri"/ >

Asp. NET built-in Session

session["one"] = DateTime.Now;            Set Value Label1.Text =convert.tostring (session["one"]);    Take value

Get and post in HTTP, ViewState principle

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.