Asp.net session, login user, cookie FAQs

Source: Internet
Author: User
Tags httpcontext sessions access database

Asp tutorial. net session, login user, cookie FAQs
This section describes common issues such as session caching, invalidation, and the inability to delete cookies.
OutPutCache custom cache: session, login user, cookie, etc.
In fact, this is also a new bottle of old wine, some time ago, this was done, and the effect and performance are not bad, so the record, I hope to help more people

Although outputcache is very important, this function is really not easy to use and cannot meet requirements for a lot of time. For example, you can customize cache dependencies, such as session, login user information, and user cookie information, more importantly, if you want to cache fragments, you can only use user controls. In this case, it is difficult to transmit values between user controls! I doubt whether the development engineers of the asp.net tutorial don't need asp.net. The developed products are still a little away from practical use !!!!

Now, you have to work on your own to solve some custom needs and support session, login user, cookie, and so on. The code is as follows:
The following code is only for testing. If you use it, change some code as needed.

Add this method to the Global. asax file:

Public override string GetVaryByCustomString (HttpContext context, string arg) {string key = string. empty; arg = arg. toLower (); // outputcache customer if (arg. contains ("user") // Login User {key + = "user:" + HttpContext. current. user. identity. name + ";";} if (arg. contains ("admin") // Is Admin User {key + = "admin:" + HttpContext. current. user. identity. name + ";-";} if (arg. contains ("hot") // Is HotR Ate List {HttpCookie cookie = Request. Cookies ["hot"]; bool isHotRate = true; if (cookie! = Null & cookie. value = "0") isHotRate = false; key + = "hot:" + isHotRate. toString () + ";";} if (arg. contains ("login") // User Is Login {key + = "login:" + context. user. identity. isAuthenticated. toString () + ";";} return key ;}
Then add the following code to the header of the call page, that is, customize the dependency in VaryByParam:

 

<% @ OutputCache Duration = "10" VaryByParam = "id; pagenum" VaryByCustom = "Admin; Login" %>

The cache dependency of this page will be: contentid (id, url parameter), pagenum (pagenum, url parameter), Admin (whether it is administrator, custom dependency) and Login (whether the user logs on, custom dependencies)

Now, we can perfectly support custom dependency caches such as Sessions, login users, and cookies, and outputcache can be intelligent. However, I still didn't think it would be easier to cache page fragments.

 


Request. Cookies. Remove () cannot be used to delete Cookies.
When asp.net (c #) is used, Request. Cookies. Remove () cannot be used to delete Cookies. It is found that the deletion can be completed by setting the expiration time to the past time. The code is as follows:
HttpCookie hc = Request. Cookies ["Value"];

Hc. Expires = DateTime. Now. AddDays (-1 );

Response. AppendCookie (hc); // This sentence must be added; otherwise, it cannot be deleted.

Sort out Cookie operations by the way:

1. Create

1. Create a single value

HttpCookie hc = new HttpCookie ("Value ");

Hc. Value = "value ";

Response. AppendCookie (hc );

2-valued creation

HttpCookie hc = new HttpCookie ("Value ");

Hc ["Value1"] = "value1 ";

Hc ["Value2"] = "value2;

Response. AppendCookie (hc );

2. Read

1. Reading a single value

String value = Request. Cookies ["Value"]. Value;

2-valued read

String value1 = Request. Cookies ["Value"] ["Value1"]. ToString ();

String value2 = Request. Cookies ["Value"] ["Value2"]. ToString ();

Cause and solution of ASP. NET Session loss

ASP. NET Session loss may occur under normal operation. Because the program is constantly being operated, the possibility of Session timeout is ruled out. In addition, the Session timeout time is set to 60 minutes, and will not time out so quickly.
Now I will write down the cause and solution.

Cause of ASP. NET Session loss:

Because the Asp.net program is configured by default, the Session settings in the Web. Config file are as follows:

<SessionState mode = 'INC' stateConnectionString = 'tcpip = 127.0.0.1: 42424 'sqlconnectionstring = 'data source = 127.0.0.1; trusted_Connection = yes 'cookieless = 'true' timeout = '60'/> www.jokedu.com
The sessionState label has an attribute mode. It can have three values: InProc and StateServer? SQLServer (size-sensitive ). The process is unstable. When some events occur, the process restarts, causing the loss of sessions stored in the process.

Under what circumstances will the process be restarted? An article by Microsoft tells us:

1. memoryLimit attribute of the processModel label in the configuration file

2. The Global. asax or Web. config file is changed.

3. The Web program (DLL) in the Bin folder is modified.

4. Anti-virus software scanned some. config files.

For more information, see PRB: Session variables are lost intermittently in ASP. NET applications.

ASP. NET Session loss solution:

In the sessionState label mentioned above, the mode attribute can have three values: StateServer and SQLServer. The two Session types are both external, so when aspnet_wp.exe is restarted, the Session will not be affected.

Set the mode to StateServer. StateServer is a Service on the local machine. You can see the Service named ASP. NET State Service in the system Service. It is not started by default. After we set the mode to StateServer, manually start the service.

In this way, we can use the StateService of the local machine to store Sessions. The Session will not be lost unless the computer restarts or the StateService breaks down (it is normal that the Session is discarded due to Session timeout ).

In addition, sessions can be saved through StateService on other computers. The specific modification is as follows. Also in the sessionState label, there is a stateConnectionString = 'tcpip = 127.0.0.1: 8080' attribute, where there is an IP address, the default is the local machine (127.0.0.1 ), you can change it to the IP address of the computer that runs the StateService service as you know, so that the Asp.net program located on different computers can interwork with Session www.yzyedu.com.

If you have higher requirements and the Session is not lost when the service period is restarted, you can set the mode to SQLServer and modify the sqlConnectionString attribute. For information on how to use SQLServer to save sessions, visit here.

When you use StateServer or SQLServer to store a Session, all objects to be saved to the Session must be serialized except the basic data type (default data type, such as int and string. You only need to put the [Serializable] label before the class to be serialized.

For example:

[Serializable]
Public class MyClass

{

......

}

For more information about serialization, see here.

So far, the ASP. NET Session loss problem is solved.

Summary of asp.net Session loss

Working Principle of Session in asp:

Asp sessions are process-dependent. The ASP sessionstate is stored in the iisprogress, and the program inetinfo.exe is also used. When the inetinfo.exe process crashes, the information is lost. In addition, restarting or disabling the IIS service will cause information loss.

Implementation of asp.net Session

ASP. NET sessions are based on the HttpModule technology. HttpModule can control the status of requests before the requests are processed. Because Sessions are used for status maintenance, therefore, it is more appropriate to use HttpModule for Session.

Cause 1:

Files in the bin directory are rewritten. asp.net has a mechanism. To ensure that the system runs normally after the dll is re-compiled, it restarts a website process, which will cause Session loss, therefore, if an access database tutorial is located in the bin directory or another file is rewritten by the system, the Session will be lost.

Cause 2:

In the folder option, if the "open folder window in a separate process" is not opened, once a new window is created, the system may consider it as a new Session and cannot access the original Session, therefore, you must enable this option. Otherwise, the Session will be lost.

Cause 3:

It seems that most of the Session loss is caused by the client, so you have to start from the client to see if the cookie has been opened.

Cause 4:

Is there a problem with the Session time settings? Will it be lost due to timeout?

Cause 5:

The maximum number of cookies in IE (20 cookies per domain) may cause session loss.

Cause 6:

The web garden mode and InProc mode are used to save the session

ASP. NET Session loss problem solving experience

1. Determine if it is caused by cause 1. You can track the modification time of a file in the bin every time you refresh the page.

2. for Session read and write logs, each read and write Session must be recorded, and the Session operations of SessionID, Session value, Page, current function, and function must be recorded, this makes it much easier to find out the cause of the loss.

3. If this is allowed, we recommend that you use state server or SQL server to save the session, which is not easy to lose.

4. Add the code to global. asa to record the creation time and end time of the Session. The Session loss caused by timeout can be recorded in SessionEnd.

5. If some codes use client scripts, such as special webpage effects to maintain the Session status, you should try to debug the script to check whether the Session is lost due to a script error.

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.