Asp. NET nine choices for maintaining user status (first)

Source: Internet
Author: User
Tags foreach config datetime form post sessions tostring urlencode
asp.net summary: asp.net provides a number of different ways to maintain data between user requests. You can use application objects, cookies, hidden fields, sessions, or cache objects, as well as their large number of methods. It is sometimes difficult to decide when to use them. This article introduces the above techniques and gives some guidance on when to use them. Although some of these technologies already exist in traditional ASP, there are. NET Framework components are changed since when they should be used. To keep the data in asp.net, you need to adjust the knowledge learned from the previous ASP's processing state.
With the advent of the web age, managing state in a stateless HTTP world has become a big problem for web developers. Several different technologies have recently emerged that store and retrieve data. In this article I will explain how ASP.net developers can request maintenance or delivery status through a page.

In ASP.net, there are several ways to keep data between users ' requests-actually too much, to make inexperienced developers confused about which object to use in a particular environment. To answer this question, the following three conditions need to be considered:

. Who needs data?

How long does the data need to be maintained?

. How large is the dataset?

By answering these questions, you can decide which object provides the best solution for keeping the data between the ASP.net application requests. Figure 1 lists the different state management objects and describes when to use them. Asp. Four new objects were added in net: Cache, Context, viewstate, and Web.config files. Asp. NET also supports traditional ASP objects, including application, cookies, Form Post, QueryString, and sessions with hidden fields. Note that the correct usage of these five data containers has changed, so experienced programmers may need to learn some knowledge when considering these familiar objects.


Keep the method who needs data to keep the data amount of time application all users entire application lifetime any size cookie a user can be very short, if the user does not delete also can very long small, simple data form Post a user to the next request (can be reused across multiple requests) any size QueryString one or a group of users to the next request (can be reused across multiple requests) small, Simple data sessions a user's activity for a period of time (typically 20 minutes) can be any size, but because the user has a separate sessions store, all of it should be minimal. Cache all users or some users can be large or small according to the need, can be simple and complex context a user request can maintain a large object, but generally do not use ViewState a user A Web Form minimum config file All users know that the profile is updated Can hold large amounts of data, often organizing small strings and XML structures

Table 1. Asp. Data Container objects in net

Application

Let's explain the object by answering the above status question decision condition. Who needs data? All users need access to it. How long does it take to keep the data? Permanently persisted, or persisted during the application lifetime. How big is the data? Can be any size--only one copy of the data exists at any given moment.

In traditional ASP, the Application object provides a location for storing frequently used but rarely changed pieces of data, such as menu content and reference data. Although application still exists as a data container in asp.net, there are other objects that are more appropriate for data that was previously saved in the application collection of traditional ASP applications.

In a traditional ASP, a Application object is an ideal choice if the saved data does not change at all during the lifetime of the application (or rarely changes, such as read-only data and mostly read-only data). The connection string is the most common piece of data saved in the application variable, but similar configuration data in asp.net is best kept in the Web.config file. If you use the Application object one of the issues to consider is that any write operations are either in the Application_OnStart event (Global.asax) or in the Application.Lock section. Although it is necessary to use Application.Lock to ensure that writes are performed correctly, it has serialized requests for application objects, which is a serious performance bottleneck for the application. Figure 2 illustrates how to use the Application object, which includes a Web form and its code files.

Application.aspx


<form id= "Application" method= "POST" runat= "Server" >
<asp:validationsummary id= "valsummary" runat= "Server" >
</asp:validationsummary>
<table>
<tr>
&LT;TD colspan= "3" >set application variable:</td>
</tr>
<tr>
<td>Name</td>
<td><asp:textbox id= "txtname" runat= "Server" ></asp:textbox>
</td>
<td><asp:requiredfieldvalidator id= "Namerequired"
runat= "Server" display= "Dynamic" errormessage= "Name is"
Required. " Controltovalidate= "Txtname" >*
</asp:requiredfieldvalidator></td>
</tr>
<tr>
<td>Value</td>
<td><asp:textbox id= "TxtValue" runat= "Server" >
</asp:textbox></td>
<td><asp:requiredfieldvalidator id= "Valuerequired"
runat= "Server" display= "Dynamic" errormessage= "Value is"
Required. " Controltovalidate= "TxtValue" >*
</asp:requiredfieldvalidator></td>
</tr>
<tr>
&LT;TD colspan= "3" ><asp:button id= "btnsubmit" runat= "Server"
text= "Update Value" ></asp:button></td>
</tr>
</table>
<asp:label id= "Lblresult" runat= "Server"/>
</form>
Application.aspx.cs
private void btnSubmit_Click (object sender, System.EventArgs e)
{
if (IsValid)
{
Application.Lock ();
Application[txtname.text] = Txtvalue.text;
Application.UnLock ();
Lblresult.text = "The value of <b>" + txtName.Text +
' </b> in ' Application object is <b> +
Application[txtname.text]. ToString () + "</b>";
}
}

Code Snippet 1. Access to application objects in ASP.net

Its output is shown in the following illustration:

Figure 1. The contents of the Application object

Note that the content of the Application object in Figure 3 is the display of trace output. Tracing is a great debugging tool, but at some point, a tracked page that is opened may appear in the product environment. If this happens, you certainly don't want to display sensitive information. This is one of the main reasons why the Application object was never recommended for storing sensitive information, such as a connection string.

Cookies

Cookies are handy when a particular user needs a specific piece of data and needs to keep the data in a variable period of time. Its lifecycle may be as short as a browser form, or it can take months and years. Cookies can be small to only a few bytes of data, because they are passed in each browser request, and their content needs to be as small as possible.

Cookies provide a flexible and powerful way to maintain data between users ' requests, which is why most dynamic sites on the Internet use them. Because cookies can store a very limited amount of data, it is best to save key fields only in cookies, and other data to be stored in a database or other server-side data container. However, because not all browsers support cookies, and it can be blocked or deleted by the user, they cannot be used to save critical data. You should handle the deletion of the user's cookies well. Finally, cookies are saved as simple plaintext text on the user's computer, so sensitive, unencrypted data cannot be saved inside it.

Figure 2. Single-valued and multivalued cookies

There is a special cookie that can hold a collection of individual values or name/value pairs. Figure 4 shows an example of a single and multiple value cookies, which are output by asp.net the built-in trace attribute. These values can be maintained in the ASP.net page using the Request.Cookies and Response.Cookies collections, as demonstrated in code Snippet 2.

Cookies.aspx.cs

Use the HttpCookie class to refer to the cookie's value and/or child value
HttpCookie cookies;
if (request.cookies[txtname.text] = = null)
cookie = new HttpCookie (txtName.Text, Txtvalue.text);
Else
cookie = Request.cookies[txtname.text];
if (TxtSubValueName.Text.Length > 0)
Cookie. Values.add (Txtsubvaluename.text, Txtsubvaluevalue.text);
Cookie. Expires = System.DateTime.Now.AddDays (1); Tomorrow
Response.appendcookie (cookie);
Retrieving the value of a cookie
if (! Request.cookies[txtname.text]. HasKeys)
Lblresult.text = "The value of the <b>" + txtName.Text + "</b>
Cookie is <b> "+ request.cookies[txtname.text]. Value.tostring () +
"</b>";
Else
{
Lblresult.text = "The value of the <b>" + txtName.Text + "</b>
Cookie is <b> "+ request.cookies[txtname.text]. Value.tostring () +
"&LT;/B&GT;, with subvalues:<br>";
foreach (String key in Request.cookies[txtname.text]. Values.keys)
{
Lblresult.text + = "[" + key + "=" +
Request.cookies[txtname.text]. Values[key]. ToString () + "]<br>";
}
}
Delete Cookies
Set the value to null and set the termination time to a certain point in the past
Response.cookies[txtname.text]. Value = null;
Response.cookies[txtname.text]. Expires =
System.DateTime.Now.AddMonths (-1); Last month

Code Snippet 2. Accessing access to cookies in asp.net

Form Post/hidden forms field

A particular user needs the form's data, and it needs to be persisted at any stage of the application termination of a single request. The data can in fact be of any size, and it is sent forward and backwards over the network with each form post.

In traditional ASP, this is the usual way to expose the state in an application, especially in a multiple-page form application. However, this technique does not fit well in asp.net, because as long as you use the postback model (that is, the page is sent back to yourself), the Web controls and viewstate automatically handle these operations. ViewState is the asp.net implementation of this technique, which I will discuss later in this article. Access to form values sent by post is done using a form collection of the HttpRequest object. In Figure 6, a asp.net page sets the ID of a user, after which it remains in a hidden form field. The subsequent request to any page retains this value until the page is linked to another user using the Submit button.

Form1.aspx


<form id= "Application" method= "POST" runat= "Server" >
<p>your Username:
<asp:label id= "Lblusername" runat= "Server"/>
</p>
<asp:panel runat= "Server" id= "Pnlsetvalue" >
<asp:validationsummary id= "valsummary" runat= "Server" >
</asp:validationsummary>
<TABLE>
<TR>
&LT;TD colspan= "3" >set Hidden Form Username variable:</td></tr>
<TR>
<TD>Username</TD>
<TD>
<asp:textbox id= "txtname" runat= "Server" ></asp:textbox></TD>
<TD>
<asp:requiredfieldvalidator id= "namerequired" runat= "Server"
Controltovalidate= "Txtname" errormessage= "Name is required."
Display= "Dynamic" >*</asp:requiredfieldvalidator></TD></TR>
<TR>
&LT;TD colspan= "3" >
<asp:button id= "btnsubmit" runat= "Server" text= "Set Value" >
</asp:button></TD></TR></TABLE>
</asp:Panel>
<asp:label id= "Lblresult" runat= "Server"/>
</form>
<form action= "form2.aspx" method= "post" name= "Form2" id= "Form2" >
<input type= "hidden" name= "username" value= "<%# username%>" >
<input type= "Submit" value= "Go to Form2.aspx"
</form>
Form1.aspx.cs
private void Page_Load (object sender, System.EventArgs e)
{
if (! IsPostBack)//new requests or requests from form2.aspx
{
Check the form collection
if (request.form["username"] = = null)
Pnlsetvalue.visible = true;
Else
{
User name values need to be set
Pnlsetvalue.visible = false;
Username = request.form["username"]. ToString ();
Lblusername.text = Username;
Data is bound to a hidden form field value
This. DataBind ();
}
}
}

private void btnSubmit_Click (object sender, System.EventArgs e)
{
if (IsValid)
{
//hidden form to set value
Pnlsetvalue.visible = false;
Username = txtName.Text;
Lblresult.text = "Username set to" + txtName.Text + ".";
Lblusername.text = Username;
this. DataBind ();
}

form2.aspx
<form id= "Application" method= "POST" runat= "Server"
<p>your Username: <asp:label id= "Lblusername" runat= "Server"/></P>
</form>
<form action= "form1.aspx" method= "post" id= "Form2" name= "Form2"
<input type= "hidden" name= "username" Value= "<%# username%>"
<input type= "Submit" value= "Go to form1.aspx"
</form>
Form2.aspx.cs
private void Page_Load (object sender, System.EventArgs e)
{
if (request.form["username"]!= NULL)
{
Username = request.form["username"]. ToString ();
Lblusername.text = Username;
this. DataBind ();
}
}
 

Code snippet 3. Using hidden form fields in asp.net

Only one server-side form can exist on a page in ASP.net, and the form must be committed to return to itself (you can still use the client form without restrictions). The Hidden form field is never used in the. NET Framework components one of the main reasons for passing data between applications is that. NET Framework component controls can use ViewState to automatically maintain their state. ViewState simply encapsulates the work contained in the use of hidden form field settings and retrieving values into a simple collection object.

QueryString

The data saved in the QueryString object is used by individual users. Its lifecycle may be as short as one request, or it may be as long as the user uses the application (if correctly constructed). This type of data is generally less than 1KB. The data in the querystring is passed in the URL and is visible to the user, so you can guess that when using this technique, sensitive data or data that can be used to control the application need to be encrypted.

In other words, QueryString is a good way to send information between asp.net Web forms. For example, if you have a data table (DataGrid) with a product list and a link-oriented product detail page on the table, using QueryString is ideal, You can include the product ID in a querystring that links to the Product Details page (for example, productdetails.aspx?id=4). Another benefit of using querystrings is that the status of the page is contained in the URL. This means that a user can put a form created by Querystrings into his favorites. When they return to the page as a collection, they will be the same as when they were collected. Obviously this is only useful when the page does not depend on all the states outside the querystring and does not make any changes.

Sensitive data, and any variables that you do not want the user to manipulate should be avoided here (unless encrypted users cannot read them). And the illegal characters in the URL must be encoded using Server.URLEncode, as shown in Figure 7. When working with a single asp.net page, ViewState is a better choice than querystring for maintenance status. For long-term data storage, cookies, sessions, or cache are more suitable as data containers than querystrings.

Querystring.aspx


<form id= "querystring" method= "POST" runat= "Server" >
<asp:validationsummary id= "valsummary" runat= "Server" >
</asp:validationsummary>
<table>
<tr>
&LT;TD colspan= "3" >set querystring variable:</td>
</tr>
<tr>
<td>Name</td>
<td><asp:textbox id= "txtname" runat= "Server" ></asp:textbox>
</td>
<td><asp:requiredfieldvalidator id= "Namerequired"
runat= "Server" display= "Dynamic" errormessage= "Name is"
Required. " Controltovalidate= "Txtname" >*
</asp:requiredfieldvalidator></td>
</tr>
<tr>
<td>Value</td>
<td><asp:textbox id= "TxtValue" runat= "Server" >
</asp:textbox></td>
<td><asp:requiredfieldvalidator id= "Valuerequired"
runat= "Server" display= "Dynamic" errormessage= "Value is"
Required. " Controltovalidate= "TxtValue" >*
</asp:requiredfieldvalidator></td>
</tr>
<tr>
&LT;TD colspan= "3" ><asp:button id= "btnsubmit" runat= "Server"
text= "Update Value" ></asp:button></td>
</tr>
</table>
<asp:label id= "Lblresult" runat= "Server"/>
<a href= "Querystring.aspx?x=1" >set querystring x equal to 1</a>
</form>
Querystring.aspx.cs
private void Page_Load (object sender, System.EventArgs e)
{
Retrieving the value of a cookie
if (Request.QueryString.HasKeys ())
{
Lblresult.text = "The values of the <b>" + txtName.Text +
"</b> querystring parameter Are:<br>";
foreach (string key in Request.QueryString.Keys)
{
Lblresult.text + = "[" + key + "=" +
Request.querystring[key]. ToString () + "]<br>";
}
}
}

private void btnSubmit_Click (object sender, System.EventArgs e)
{
if (IsValid)
{
String url = "Querystring.aspx?";
foreach (string key in Request.QueryString.Keys)
{
url = + key + "=" + Request.querystring[key]. ToString () + "&";
}
Response.Redirect (url + txtname.text + "=" +
Server.URLEncode (Txtvalue.text));
}
}

Code snippet 4. Using Querystrings to pass data in asp.net


Sessions

Sessions data is specific to a particular user. Its lifetime is the time that the user continues to request, plus a period of time (typically 20 minutes). Sessions can maintain a large or small amount of data, but if the application is used for hundreds of thousands of users, the total storage should be kept to a minimum.

Unfortunately, the reputation of sessions objects in traditional ASP is bad because it constrains applications to specific computers, blocking user grouping and web-wide scalability. There are few problems with asp.net because changing the location of the sessions is simple. By default (best performance), sessions data is still stored in memory on the local Web server, but ASP.net supports the use of external state servers or databases to manage sessions data.

Using the Sessions object is simple, and it has the same syntax as a traditional ASP. However, the sessions object is a very inefficient method of saving user data, because it remains in memory for some time even after the user stops using the application. This has a serious impact on the scalability of very busy sites. Other options allow more control over the release of memory, such as a cache object that may be more suitable for large data values. and by default ASP.net sessionss relies on cookies, so if the user forbids or does not support COOKIE,SESSIONSS, it does not work, but it can be configured SESSIONSS support cookies Independent. For small amounts of data, the Sessionss object is an excellent place to save specific data that only needs to be maintained in the user's current conversation. The following example shows how to set and retrieve values from a Sessionss object:


private void btnSubmit_Click (object sender, System.EventArgs e)
{
if (IsValid)
{
Set Sessions value
Sessions[txtname.text] = Txtvalue.text;

Read and display just the settings
Lblresult.text = "The value of <b>" + txtName.Text + "</b> in" Sessions object is <b> + sessions[txt Name.text]. ToString () + "</b>";
}
}

This web form is almost identical to the one used in the Application object, and the contents of the sessions collection are also visible when page tracking is allowed.
What you need to keep in mind is that even if you don't use it, SESSIONSS will have application overhead. Setting the SESSIONSS state to read-only can also optimize pages that need only to be read without writing data. You can configure SESSIONSS with one of the following two ways:


<%@ Page enablesessionsstate= "false"%>
<%@ Page enablesessionsstate= "ReadOnly"%>

asp.net sessionss can be configured in sessionsstate elements in Web.config or machine.config. The following are examples of settings in Web.config:


<sessionsstate timeout= "Ten" cookieless= "false" mode= "Inproc"/>




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.