Asp. netSession Sharing Solution

Source: Internet
Author: User
Tags subdomain name

Asp. netSession Sharing Solution

 

1. iis7.0webconfig Configuration

  
          
     
             
     
  
 


2. Intercept the class and reset the sessionid value.

 

namespace aspnetstate_webformtest{    public class mysession : IHttpModule    {        private string m_RootDomain = string.Empty;        #region IHttpModule Members        public void Dispose()        {        }        public void Init(HttpApplication context)        {            m_RootDomain = test.com;            Type stateServerSessionProvider = typeof(HttpSessionState).Assembly.GetType(System.Web.SessionState.OutOfProcSessionStateStore);            FieldInfo uriField = stateServerSessionProvider.GetField(s_uribase, BindingFlags.Static | BindingFlags.NonPublic);            if (uriField == null)                throw new ArgumentException(UriField was not found);            uriField.SetValue(null, m_RootDomain);            context.EndRequest += new System.EventHandler(context_EndRequest);        }        void context_EndRequest(object sender, System.EventArgs e)        {            HttpApplication app = sender as HttpApplication;            for (int i = 0; i < app.Context.Response.Cookies.Count; i++)            {                if (app.Context.Response.Cookies[i].Name == ASP.NET_SessionId)                {                    app.Context.Response.Cookies[i].Domain = m_RootDomain;                }            }        }        #endregion    }}

3. Simulate Nginx configuration for the same domain name

 

 

upstream myServer {        server localhost:8024;     server 172.18.89.5:8024; }server{  listen       1009;        server_name  localhost ;   location / {            proxy_pass http://myServer/;            proxy_set_header Host $host;            proxy_set_header X-Real-IP $remote_addr;            proxy_redirect off;        }}


 

 

 

Refer:

Session Sharing Solution

1. The client SessionID value is unique;

For different domain names: primary domain name, subdomain name, cross-site domain name, or cross-server domain name, users will generate different sessionids when opening the page,

To enable these sites to log on only once, we need to solve the SessionID problem. SessionID must be generated only once in these sites with shared sessions. SessionID indicates the key value of the cookie stored on the client as ASP. A string of NET_SessionId (which can also be stored in the URL, which is not described here). Therefore, you only need to make the SP. the NET_SessionId must be unique.

Because each client will generate a SessionID when it is opened, what we need to do is reset the SessionID. We can override SessionID when inheriting HttpModule and ending the request.

 

    public class MakeSessionIDOneOnly : IHttpModule    {        private string m_RootDomain = string.Empty;        #region IHttpModule Members        public void Dispose()        {                    }        public void Init(HttpApplication context)        {            m_RootDomain = ConfigurationManager.AppSettings[RootDomain];            Type stateServerSessionProvider = typeof(HttpSessionState).Assembly.GetType(System.Web.SessionState.OutOfProcSessionStateStore);            FieldInfo uriField = stateServerSessionProvider.GetField(s_uribase, BindingFlags.Static | BindingFlags.NonPublic);            if (uriField == null)                throw new ArgumentException(UriField was not found);            uriField.SetValue(null, m_RootDomain);                        context.EndRequest += new System.EventHandler(context_EndRequest);        }        void context_EndRequest(object sender, System.EventArgs e)        {            HttpApplication app = sender as HttpApplication;            for (int i = 0; i < app.Context.Response.Cookies.Count; i++)            {                if (app.Context.Response.Cookies[i].Name == ASP.NET_SessionId)                {                    app.Context.Response.Cookies[i].Domain = m_RootDomain;                }            }        }        #endregion    }

 

To use the above Code, you must configure the following node items.

 

 

2. Sharing Session values;

Configure sessionState to set nodes and use StateServer or SQLServer to share sessions.

To achieve cross-server sharing, you must configure in Web. config:

In addition, the same Web. config must be used for site configuration on different servers, and the Directory configuration for each site must be the same.

 

2.1 use StateServer:

The server that stores the Session must enable the StateServer: ASP. NET status service. The Session is lost only when the machine restarts.

If StateServer is stored locally, IpAddress is 127.0.0.1. If StateServer is a remote server, IpAddress is the remote server IP address, and the registry key is modified as follows:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINESYSTEMCurrentControlSetServicesaspnet_stateParameters]

Port = dword: Drawing a5b8

AllowRemoteConnection = dword: 00000001

 

2.2 Use SQLServer:

The SQLServer proxy service must be enabled. This service is used to clear expired sessions. If no service is enabled, the Session will not expire.

When SQLServer is used, the Session will not be lost after the machine is restarted.

Web. config Configuration:

 

Database Configuration:

Use aspnet_regsql.exe

After ASP. NET 2.0133, The aspnet_regsql.exe tool can be used to conveniently configure the Session database. This tool is located in the Microsoft. NETFramework version folder of the system root directory on the Web server.

Example:

Aspnet_regsql.exe-S.-U sa-P 123456-ssadd-sstype p

-S parameters:

Indicates the name of the database instance. You can use "." to indicate the name of the local database.

-U and-P parameters:

Indicates the user name and password.

-E parameter:

You can select a group in-U-P and-E.-E indicates that the current system user logs on to the database through windows authentication, and-U-P indicates that the SQL Server user logs on to the database.

-Ssadd/-ssremove parameters:

-Ssadd indicates that the Session database is added, and-ssremove indicates that the Session database is removed.

Sstype parameter description:

T

Store session data in the SQL Server tempdb database. This is the default setting. If session data is stored in the tempdb database, session data is lost when SQL Server is restarted.

P

Store session data in the ASPState database instead of the tempdb database.

C

Store session data in a custom database. If the c option is specified, you must also use the-d option to include the name of the custom database.

 

SessionState parameter description:

Attribute

Description

AllowCustomSqlDatabase

Optional Boolean attribute.

Specifies whether the session Status SQL database can be a custom database (rather than an ASP. NET default database ). If the value is false, the initial directory or database cannot be specified as the value of the sqlConnectionString attribute. The default session status is the ASPState database. For more information, see session Status mode.

This attribute is a new attribute in. NET Framework 2.0.

The default value is false.

Cookieless

Optional.

Specifies how to use cookies for Web applications.

The cookieless attribute can be one of the following possible values. The default value is UseCookies.

Value

Description

AutoDetect

ASP. NET determines whether the request browser or request device supports cookies. If you request a browser or a device to support cookies, AutoDetect uses cookies to retain user data. Otherwise, an identifier is used in the query string. If the browser or device supports cookies but the cookies are disabled, the request function still uses cookies.

UseCookies

Whether the browser or device supports cookies, cookies are used to retain user data.

UseDeviceProfile

ASP. NET determines whether to use cookies Based on HttpBrowserCapabilities settings. If the HttpBrowserCapabilities setting indicates that the browser or device supports cookies, a Cookie is used. Otherwise, an identifier is used in the query string.

UseUri

Whether the browser or device supports cookies, the query string is used to store identifiers.

 

CookieName

Optional String attributes.

The name of the Cookie that stores the session identifier.

This attribute is a new attribute in. NET Framework 2.0.

The default value is ASP. NET_SessionId.

CustomProvider

Optional String attributes.

Specifies the name of the custom session Status provider used to store and retrieve session status data. The provider specifies in the providers element. This provider is used only when the session Status mode is set to Custom. For more information, see session Status mode.

This attribute is a new attribute in. NET Framework 2.0.

The default value is a null string ().

Mode

Optional SessionStateMode attribute.

Specifies the location where the session status value is stored. For more information, see session Status mode.

The mode attribute can be one of the following values. The default value is InProc.

Value

Description

Custom

Session status information is stored in the Custom Data storage area.

InProc

The session is in the state of processing the ASP. NET auxiliary process.

Off

The session status is disabled.

SQLServer

The session Status stores the status information using the SQL Server database outside the process.

StateServer

The session status is stored by the out-of-process ASP. NET status service.

 

PartitionResolverType

Optional String attributes.

Specifies where the session status is stored. If the partitionResolverType attribute specifies a value, the sqlConnectionString and stateConnectionString attributes are ignored. The connection string returned by the PartitionResolverType attribute is used for each request, connecting the rest of the request to the appropriate server location. If the connection string is invalid, ASP. NET raises an exception, which is the same as the exception thrown when the configured server connection string is invalid. This attribute is used to divide session status data on multiple backend nodes in SQL or status server mode.

This attribute is a new attribute in. NET Framework 2.0.

The default value is an empty string.

RegenerateExpiredSessionId

Optional Boolean attribute.

Specify whether to re-issue the session ID when the client specifies an expired session ID. By default, when regenerateExpiredSessionId is enabled, the session ID is reissued only in cookieless mode. For more information, see IsCookieless.

This attribute is a new attribute in. NET Framework 2.0.

The default value is true.

SqlCommandTimeout

Optional TimeSpan attributes.

Specify the duration timeout (in seconds) of the SQL command in SQL Server session Status mode ). Duration timeout is the time (in seconds) when the SQL command can be idle. After this time expires, the command will be canceled.

This attribute is a new attribute in. NET Framework 2.0.

The default value is 0:00:30 (30 seconds ).

SqlConnectionString

Optional String attributes.

Specify the connection string for the computer running SQL Server. This attribute is required when the mode attribute is set to the SQLServer value. For more information, see session Status mode.

Note:

To improve the security of your applications in SQLServer mode, use protected configurations to encrypt the sessionState section to help protect the sqlConnectionString value.

The default value is data source = 127.0.0.1; Integrated Security = SSPI.

StateConnectionString

Optional String attributes.

Specify the name, address, and port of the server that stores the session Status remotely. The port value must be 42424. This attribute is required when mode is set to StateServer. Make sure that the server running ASP. NET Status Service is a remote server that stores session status information. This service is installed with ASP. NET. The default value is %systemroot=microsoft.netframeworkversionnumberaspnet_state.exe. For more information, see session Status mode.

Note:

To improve the security of your applications when using StateServer mode, use protected configurations to encrypt To help protect the stateConnectionString value.

The default value is tcpip = 127.0.0.1: 42424.

StateNetworkTimeout

Optional TimeSpan attributes.

Specify the time (in seconds) when the TCP/IP network connection between the Web server and the status server can be idle. After this time, the request will be canceled. This attribute is used when the mode attribute is set to the StateServer value.

The default value is 10 seconds.

Timeout

Optional TimeSpan attributes.

Specify the number of minutes that the session can be idle before it is abandoned. For in-process and State server modes, the timeout attribute cannot be set to a value greater than 525,601 minutes (1 year.

The Session timeout configuration is only applicable to ASP. NET pages. Changing the Session timeout value does not affect the Session timeout time on the ASP page. Similarly, changing the Session Timeout time on the ASP page does not affect the Session Timeout time on the ASP. NET page.

The default value is 20 minutes.

UseHostingIdentity

Optional Boolean attribute.

Specifies whether the session status will be restored to the host ID or simulated by the client.

If true, ASP. NET uses one of the following process creden: to connect to the session Status store:

Host process. For Microsoft Internet Information Services [IIS] 5 and 5.1, the process is ASPNET, and for Microsoft Windows Server 2003, the process is network service.

The application simulated identity. This credential is used when the following configuration is used:

If it is false, ASP. NET uses the creden currently associated with the operating system thread of the current request to connect to the session Status store. For client simulation, ASP. NET uses the Security creden。 negotiated with the browser to connect to the session Status store. If this parameter is set to false, ASP. NET does not return to the process ID or simulated Application ID when connecting to the session Status bucket. For more information, see ASP. NET simulation.

This attribute is a new attribute in. NET Framework 2.0.

The default value is true.

Note:

In. in NET Framework 1.1, if the mode attribute is set to SQLServer and the simulation is valid on the client, ASP. NET use from ASP.. NET client simulated client creden。 connect to the computer running SQL Server.

 

Inherited attributes

Optional attributes.

Attributes inherited by all section elements.

 

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.