- State Management In Asp.net Web Api
- State Management In Asp.net Mvc
- State Management In Asp.net Tutorial
By Rick Anderson, Steve Smith, Diana LaRose, and Luke Latham
HTTP is a stateless protocol. Without taking additional steps, HTTP requests are independent messages that don't retain user values or app state. This article describes several approaches to preserve user data and app state between requests.
View or download sample code (how to download)
State management
State can be stored using several approaches. Each approach is described later in this topic.
Storage approach | Storage mechanism |
---|---|
Cookies | HTTP cookies (may include data stored using server-side app code) |
Session state | HTTP cookies and server-side app code |
TempData | HTTP cookies or session state |
Query strings | HTTP query strings |
Hidden fields | HTTP form fields |
HttpContext.Items | Server-side app code |
Cache | Server-side app code |
Dependency Injection | Server-side app code |
Cookies
Cookies store data across requests. Because cookies are sent with every request, their size should be kept to a minimum. Ideally, only an identifier should be stored in a cookie with the data stored by the app. Most browsers restrict cookie size to 4096 bytes. Only a limited number of cookies are available for each domain.
Because cookies are subject to tampering, they must be validated by the app. Cookies can be deleted by users and expire on clients. However, cookies are generally the most durable form of data persistence on the client.
Cookies are often used for personalization, where content is customized for a known user. The user is only identified and not authenticated in most cases. The cookie can store the user's name, account name, or unique user ID (such as a GUID). You can then use the cookie to access the user's personalized settings, such as their preferred website background color.
Be mindful of the European Union General Data Protection Regulations (GDPR) when issuing cookies and dealing with privacy concerns. For more information, see General Data Protection Regulation (GDPR) support in ASP.NET Core.
Session state
Session state is an ASP.NET Core scenario for storage of user data while the user browses a web app. Session state uses a store maintained by the app to persist data across requests from a client. The session data is backed by a cache and considered ephemeral data—the site should continue to function without the session data. Critical application data should be stored in the user database and cached in session only as a performance optimization.
Note
Session isn't supported in SignalR apps because a SignalR Hub may execute independent of an HTTP context. For example, this can occur when a long polling request is held open by a hub beyond the lifetime of the request's HTTP context.
ASP.NET Core maintains session state by providing a cookie to the client that contains a session ID, which is sent to the app with each request. The app uses the session ID to fetch the session data.
Session state exhibits the following behaviors:
- Because the session cookie is specific to the browser, sessions aren't shared across browsers.
- Session cookies are deleted when the browser session ends.
- If a cookie is received for an expired session, a new session is created that uses the same session cookie.
- Empty sessions aren't retained—the session must have at least one value set into it to persist the session across requests. When a session isn't retained, a new session ID is generated for each new request.
- The app retains a session for a limited time after the last request. The app either sets the session timeout or uses the default value of 20 minutes. Session state is ideal for storing user data that's specific to a particular session but where the data doesn't require permanent storage across sessions.
- Session data is deleted either when the ISession.Clear implementation is called or when the session expires.
- There's no default mechanism to inform app code that a client browser has been closed or when the session cookie is deleted or expired on the client.
- The ASP.NET Core MVC and Razor pages templates include support for General Data Protection Regulation (GDPR). Session state cookies aren't marked essential by default, so session state isn't functional unless tracking is permitted by the site visitor. For more information, see General Data Protection Regulation (GDPR) support in ASP.NET Core.
Warning
Don't store sensitive data in session state. The user might not close the browser and clear the session cookie. Some browsers maintain valid session cookies across browser windows. A session might not be restricted to a single user—the next user might continue to browse the app with the same session cookie.
The in-memory cache provider stores session data in the memory of the server where the app resides. In a server farm scenario:
- Use sticky sessions to tie each session to a specific app instance on an individual server. Azure App Service uses Application Request Routing (ARR) to enforce sticky sessions by default. However, sticky sessions can affect scalability and complicate web app updates. A better approach is to use a Redis or SQL Server distributed cache, which doesn't require sticky sessions. For more information, see Distributed caching in ASP.NET Core.
- The session cookie is encrypted via IDataProtector. Data Protection must be properly configured to read session cookies on each machine. For more information, see ASP.NET Core Data Protection and Key storage providers.
Configure session state
The Microsoft.AspNetCore.Session package, which is included in the Microsoft.AspNetCore.App metapackage, provides middleware for managing session state. To enable the session middleware,
Startup
must contain:- Any of the IDistributedCache memory caches. The
IDistributedCache
implementation is used as a backing store for session. For more information, see Distributed caching in ASP.NET Core. - A call to AddSession in
ConfigureServices
. - A call to UseSession in
Configure
.
The following code shows how to set up the in-memory session provider with a default in-memory implementation of
IDistributedCache
:The order of middleware is important. In the preceding example, an
InvalidOperationException
exception occurs when UseSession
is invoked after UseMvc
. For more information, see Middleware Ordering.HttpContext.Session is available after session state is configured.
HttpContext.Session
can't be accessed before UseSession
has been called.A new session with a new session cookie can't be created after the app has begun writing to the response stream. The exception is recorded in the web server log and not displayed in the browser.
Load session state asynchronously
The default session provider in ASP.NET Core loads session records from the underlying IDistributedCache backing store asynchronously only if the ISession.LoadAsync method is explicitly called before the TryGetValue, Set, or Remove methods. If
LoadAsync
isn't called first, the underlying session record is loaded synchronously, which can incur a performance penalty at scale.To have apps enforce this pattern, wrap the DistributedSessionStore and DistributedSession implementations with versions that throw an exception if the
LoadAsync
method isn't called before TryGetValue
, Set
, or Remove
. Register the wrapped versions in the services container.Session options
To override session defaults, use SessionOptions.
Option | Description |
---|---|
Cookie | Determines the settings used to create the cookie. Name defaults to SessionDefaults.CookieName (.AspNetCore.Session ). Path defaults to SessionDefaults.CookiePath (/ ). SameSite defaults to SameSiteMode.Lax (1 ). HttpOnly defaults to true . IsEssential defaults to false . |
IdleTimeout | The IdleTimeout indicates how long the session can be idle before its contents are abandoned. Each session access resets the timeout. This setting only applies to the content of the session, not the cookie. The default is 20 minutes. |
IOTimeout | The maximum amount of time allowed to load a session from the store or to commit it back to the store. This setting may only apply to asynchronous operations. This timeout can be disabled using InfiniteTimeSpan. The default is 1 minute. |
Session uses a cookie to track and identify requests from a single browser. By default, this cookie is named
.AspNetCore.Session
, and it uses a path of /
. Because the cookie default doesn't specify a domain, it isn't made available to the client-side script on the page (because HttpOnly defaults to true
).To override cookie session defaults, use
SessionOptions
:The app uses the IdleTimeout property to determine how long a session can be idle before its contents in the server's cache are abandoned. This property is independent of the cookie expiration. Each request that passes through the Session Middleware resets the timeout.
Session state is non-locking. If two requests simultaneously attempt to modify the contents of a session, the last request overrides the first.
Session
is implemented as a coherent session, which means that all the contents are stored together. When two requests seek to modify different session values, the last request may override session changes made by the first.Set and get Session values
Session state is accessed from a Razor Pages PageModel class or MVC Controller class with HttpContext.Session. This property is an ISession implementation.
The
ISession
implementation provides several extension methods to set and retrieve integer and string values. The extension methods are in the Microsoft.AspNetCore.Http namespace (add a using Microsoft.AspNetCore.Http;
statement to gain access to the extension methods) when the Microsoft.AspNetCore.Http.Extensions package is referenced by the project. Both packages are included in the Microsoft.AspNetCore.App metapackage.ISession
extension methods:The following example retrieves the session value for the
IndexModel.SessionKeyName
key (_Name
in the sample app) in a Razor Pages page:The following example shows how to set and get an integer and a string:
State Management In Asp.net Web Api
All session data must be serialized to enable a distributed cache scenario, even when using the in-memory cache. Minimal string and number serializers are provided (see the methods and extension methods of ISession). Complex types must be serialized by the user using another mechanism, such as JSON.
Add the following extension methods to set and get serializable objects:
The following example shows how to set and get a serializable object with the extension methods:
TempData
ASP.NET Core exposes the TempData property of a Razor Pages page model or TempData of an MVC controller. This property stores data until it's read. The Keep and Peek methods can be used to examine the data without deletion. TempData is particularly useful for redirection when data is required for more than a single request. TempData is implemented by TempData providers using either cookies or session state.
TempData providers
The cookie-based TempData provider is used by default to store TempData in cookies.
The cookie data is encrypted using IDataProtector, encoded with Base64UrlTextEncoder, then chunked. Windows needs your current credentials win 10. Because the cookie is chunked, the single cookie size limit found in ASP.NET Core 1.x doesn't apply. The cookie data isn't compressed because compressing encrypted data can lead to security problems such as the CRIME and BREACH attacks. For more information on the cookie-based TempData provider, see CookieTempDataProvider.
Choose a TempData provider
Choosing a TempData provider involves several considerations, such as:
- Does the app already use session state? If so, using the session state TempData provider has no additional cost to the app (aside from the size of the data).
- Does the app use TempData only sparingly for relatively small amounts of data (up to 500 bytes)? If so, the cookie TempData provider adds a small cost to each request that carries TempData. If not, the session state TempData provider can be beneficial to avoid round-tripping a large amount of data in each request until the TempData is consumed.
- Does the app run in a server farm on multiple servers? If so, there's no additional configuration required to use the cookie TempData provider outside of Data Protection (see ASP.NET Core Data Protection and Key storage providers).
Note
Most web clients (such as web browsers) enforce limits on the maximum size of each cookie, the total number of cookies, or both. When using the cookie TempData provider, verify the app won't exceed these limits. Consider the total size of the data. Account for increases in cookie size due to encryption and chunking.
Configure the TempData provider
The cookie-based TempData provider is enabled by default.
To enable the session-based TempData provider, use the AddSessionStateTempDataProvider extension method:
The order of middleware is important. In the preceding example, an
InvalidOperationException
exception occurs when UseSession
is invoked after UseMvc
. For more information, see Middleware Ordering.Important
If targeting .NET Framework and using the session-based TempData provider, add the Microsoft.AspNetCore.Session package to the project.
Query strings
A limited amount of data can be passed from one request to another by adding it to the new request's query string. This is useful for capturing state in a persistent manner that allows links with embedded state to be shared through email or social networks. Because URL query strings are public, never use query strings for sensitive data.
In addition to unintended sharing, including data in query strings can create opportunities for Cross-Site Request Forgery (CSRF) attacks, which can trick users into visiting malicious sites while authenticated. Attackers can then steal user data from the app or take malicious actions on behalf of the user. Any preserved app or session state must protect against CSRF attacks. For more information, see Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks.
Hidden fields
Data can be saved in hidden form fields and posted back on the next request. This is common in multi-page forms. Because the client can potentially tamper with the data, the app must always revalidate the data stored in hidden fields.
HttpContext.Items
The HttpContext.Items collection is used to store data while processing a single request. The collection's contents are discarded after a request is processed. The
Items
collection is often used to allow components or middleware to communicate when they operate at different points in time during a request and have no direct way to pass parameters.In the following example, middleware adds
isVerified
to the Items
collection.Later in the pipeline, another middleware can access the value of
isVerified
:For middleware that's only used by a single app,
string
keys are acceptable. Middleware shared between app instances should use unique object keys to avoid key collisions. The following example shows how to use a unique object key defined in a middleware class:Other code can access the value stored in
HttpContext.Items
using the key exposed by the middleware class:This approach also has the advantage of eliminating the use of key strings in the code.
Cache
Caching is an efficient way to store and retrieve data. The app can control the lifetime of cached items.
Cached data isn't associated with a specific request, user, or session. Be careful not to cache user-specific data that may be retrieved by other users' requests.
For more information, see Response caching in ASP.NET Core.
Dependency Injection
Use Dependency Injection to make data available to all users:
- Define a service containing the data. For example, a class named
MyAppData
is defined: - Add the service class to
Startup.ConfigureServices
: - Consume the data service class:
Common errors
- 'Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'.'This is usually caused by failing to configure at least one
IDistributedCache
implementation. For more information, see Distributed caching in ASP.NET Core and Cache in-memory in ASP.NET Core. - In the event that the session middleware fails to persist a session (for example, if the backing store isn't available), the middleware logs the exception and the request continues normally. This leads to unpredictable behavior.For example, a user stores a shopping cart in session. The user adds an item to the cart but the commit fails. The app doesn't know about the failure so it reports to the user that the item was added to their cart, which isn't true.The recommended approach to check for errors is to call
await feature.Session.CommitAsync();
from app code when the app is done writing to the session.CommitAsync
throws an exception if the backing store is unavailable. IfCommitAsync
fails, the app can process the exception.LoadAsync
throws under the same conditions where the data store is unavailable.
Additional resources
- Let's look closer at how Web Forms … excels at state management. … In Visual Studio, run the Web Forms application project, … make sure to set the start page to the newsletter … sign up form we added earlier. … Enter an email address, and then click submit. … The page just posted back to the server. … Notice that after it reloaded, … the email address is still populated. … The asp.net page framework preserves these values … across round trips to the server. … It does this using a mechanism called Viewstate. … Right click the page in the browser and select … view page source. … Notice this hidden form field on line twelve, … where the name starts with two leading underscores … and Viewstate in capital letters. … When the HTML gets rendered, the current state of the page … and value save during post back are stored here. … The state information is serialized as a base sixty four … encoded string in this value attribute. … When the page posts back to the server, … the contents of Viewstate are also sent along. …
Released
3/7/2019 ASP.NET boasts frameworks you can leverage to build robust web applications. In this course, Janan Siam helps you get up and running with this mature framework from Microsoft. Janan explores the framework and IDE, as well as the tools you need to manage data, build RESTful services, and establish real-time web connections. Learn how to build web applications with ASP.NET MVC, create dynamic web content with ASP.NET Web Pages and Razor syntax, work with ASP.NET SignalR, and more. Topics include:- Capabilities of the ASP.NET platform
- Running and debugging a web application
- Creating a Web Forms application
- Building dynamic pages with Razor syntax
- Working with models and forms in ASP.NET MVC
- Data access with Entity Framework
- Building RESTful services using ASP.NET Web API
- Real-time web functionality with SignalR
2h 9m
Duration
Show MoreShow Less
Join the DZone community and get the full member experience.
Join For FreeThere are two types of state management - server side and client side. In this post I'm going to introduce the client side state management and explain when to choose client side or server side state management.
Client Side State Management Techniques
Client side state management include the following techniques:
- ViewState - ASP.NET track the state of the controls on the pages through
the ViewState. Also, ViewState is used to store small custom values.
Don't hold big custom data object because it will affect the performance of
your web page. - Hidden fields - hidden fields are html input control with a type of hidden -
<input type='hidden'>. They are used to store data in the html without presenting
the data in the browser. The data of hidden field is available when the form is
processed or when using javascript. The ViewState use hidden field to save its
data. You can use the View Source operation (if enabled) to scan the web page's
source and to look for hidden fields. - Query strings - query string state is stored in the URL that is sent to the browser.
Unlike ViewState and hidden fields, the user can see the values without using
special operations like View Source. The parameters are passed in the URL
separated by the & symbol.
For example, in the following URL the query string is built out of two data
parameters, a and b, which hold the values 1 and 2 - http://www.srl.co.il?a=1;b=2. - Cookies - the cookies store their values in the user's browser and the browser
send them back to the server every time a request is performed.
Cookies are maintained during the session of a user in the web site and therefore
can be used in multiple web pages of the site. - Control state - when building custom controls you should use the control state
to save your state if EnableViewState property is set to false.
This is the only reason to use this technique.
How do you know when to choose the client side or server side state management?
When to Choose Client Side State Management
Choose client side for better scalability and support multiple servers. The client side helps to get better scalability by storing state data in the user's browser instead of using the web server's memory. The client side support multiple servers because all the state is located in the browser. This way when you are redirected to another server you don't need to worry about your state.
The thing I wrote doesn't means that you can't use server side state management for the supporting of multiple server. To enable server side state management to be able to support multiple servers you'll have to use centralized state management (state server or store state in database) or you'll have to use techniques like sticky
connection for load balancing.
connection for load balancing.
When to Choose Server Side State Management
Choose server side for better security and to reduce bandwidth and web page's size. Server side state management is more secure. The state is saved on the server and therefore isn't delivered to the client.
Confidential state data shouldn't be used with client side state management. Server side reduce the traffic to and from the client because data isn't sent to the browser and it's saved on the server. You should always remember that using client side state management sends data to the user's browser and that data is sent back to the server
every time. This situation increases bandwidth usage and therefore your application will be less responsive and you'll suffer from performance issues.
In the next post I'll drill down into the client side techniques and explain how to use them. Confidential state data shouldn't be used with client side state management. Server side reduce the traffic to and from the client because data isn't sent to the browser and it's saved on the server. You should always remember that using client side state management sends data to the user's browser and that data is sent back to the server
every time. This situation increases bandwidth usage and therefore your application will be less responsive and you'll suffer from performance issues.
Like This Article? Read More From DZone
Published at DZone with permission of Gil Fink , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
-->By Rick Anderson, Steve Smith, Diana LaRose, and Luke Latham
HTTP is a stateless protocol. Without taking additional steps, HTTP requests are independent messages that don't retain user values or app state. This article describes several approaches to preserve user data and app state between requests.
View or download sample code (how to download)
State management
State can be stored using several approaches. Each approach is described later in this topic.
Storage approach | Storage mechanism |
---|---|
Cookies | HTTP cookies (may include data stored using server-side app code) |
Session state | HTTP cookies and server-side app code |
TempData | HTTP cookies or session state |
Query strings | HTTP query strings |
Hidden fields | HTTP form fields |
HttpContext.Items | Server-side app code |
Cache | Server-side app code |
Dependency Injection | Server-side app code |
Cookies
Cookies store data across requests. Because cookies are sent with every request, their size should be kept to a minimum. Ideally, only an identifier should be stored in a cookie with the data stored by the app. Most browsers restrict cookie size to 4096 bytes. Only a limited number of cookies are available for each domain.
Because cookies are subject to tampering, they must be validated by the app. Cookies can be deleted by users and expire on clients. However, cookies are generally the most durable form of data persistence on the client.
Cookies are often used for personalization, where content is customized for a known user. The user is only identified and not authenticated in most cases. The cookie can store the user's name, account name, or unique user ID (such as a GUID). You can then use the cookie to access the user's personalized settings, such as their preferred website background color.
Be mindful of the European Union General Data Protection Regulations (GDPR) when issuing cookies and dealing with privacy concerns. For more information, see General Data Protection Regulation (GDPR) support in ASP.NET Core.
Session state
Session state is an ASP.NET Core scenario for storage of user data while the user browses a web app. Session state uses a store maintained by the app to persist data across requests from a client. The session data is backed by a cache and considered ephemeral data—the site should continue to function without the session data. Critical application data should be stored in the user database and cached in session only as a performance optimization.
Note
Session isn't supported in SignalR apps because a SignalR Hub may execute independent of an HTTP context. For example, this can occur when a long polling request is held open by a hub beyond the lifetime of the request's HTTP context.
ASP.NET Core maintains session state by providing a cookie to the client that contains a session ID, which is sent to the app with each request. The app uses the session ID to fetch the session data.
Session state exhibits the following behaviors:
- Because the session cookie is specific to the browser, sessions aren't shared across browsers.
- Session cookies are deleted when the browser session ends.
- If a cookie is received for an expired session, a new session is created that uses the same session cookie.
- Empty sessions aren't retained—the session must have at least one value set into it to persist the session across requests. When a session isn't retained, a new session ID is generated for each new request.
- The app retains a session for a limited time after the last request. The app either sets the session timeout or uses the default value of 20 minutes. Session state is ideal for storing user data that's specific to a particular session but where the data doesn't require permanent storage across sessions.
- Session data is deleted either when the ISession.Clear implementation is called or when the session expires.
- There's no default mechanism to inform app code that a client browser has been closed or when the session cookie is deleted or expired on the client.
- The ASP.NET Core MVC and Razor pages templates include support for General Data Protection Regulation (GDPR). Session state cookies aren't marked essential by default, so session state isn't functional unless tracking is permitted by the site visitor. For more information, see General Data Protection Regulation (GDPR) support in ASP.NET Core.
Warning
Don't store sensitive data in session state. The user might not close the browser and clear the session cookie. Some browsers maintain valid session cookies across browser windows. A session might not be restricted to a single user—the next user might continue to browse the app with the same session cookie.
The in-memory cache provider stores session data in the memory of the server where the app resides. In a server farm scenario:
- Use sticky sessions to tie each session to a specific app instance on an individual server. Azure App Service uses Application Request Routing (ARR) to enforce sticky sessions by default. However, sticky sessions can affect scalability and complicate web app updates. A better approach is to use a Redis or SQL Server distributed cache, which doesn't require sticky sessions. For more information, see Distributed caching in ASP.NET Core.
- The session cookie is encrypted via IDataProtector. Data Protection must be properly configured to read session cookies on each machine. For more information, see ASP.NET Core Data Protection and Key storage providers.
Configure session state
The Microsoft.AspNetCore.Session package, which is included in the Microsoft.AspNetCore.App metapackage, provides middleware for managing session state. To enable the session middleware,
Startup
must contain:- Any of the IDistributedCache memory caches. The
IDistributedCache
implementation is used as a backing store for session. For more information, see Distributed caching in ASP.NET Core. - A call to AddSession in
ConfigureServices
. - A call to UseSession in
Configure
.
The following code shows how to set up the in-memory session provider with a default in-memory implementation of
IDistributedCache
:The order of middleware is important. In the preceding example, an
InvalidOperationException
exception occurs when UseSession
is invoked after UseMvc
. For more information, see Middleware Ordering.HttpContext.Session is available after session state is configured.
HttpContext.Session
can't be accessed before UseSession
has been called.A new session with a new session cookie can't be created after the app has begun writing to the response stream. The exception is recorded in the web server log and not displayed in the browser.
Load session state asynchronously
The default session provider in ASP.NET Core loads session records from the underlying IDistributedCache backing store asynchronously only if the ISession.LoadAsync method is explicitly called before the TryGetValue, Set, or Remove methods. If
LoadAsync
isn't called first, the underlying session record is loaded synchronously, which can incur a performance penalty at scale.To have apps enforce this pattern, wrap the DistributedSessionStore and DistributedSession implementations with versions that throw an exception if the
LoadAsync
method isn't called before TryGetValue
, Set
, or Remove
. Register the wrapped versions in the services container.Session options
To override session defaults, use SessionOptions.
Option | Description |
---|---|
Cookie | Determines the settings used to create the cookie. Name defaults to SessionDefaults.CookieName (.AspNetCore.Session ). Path defaults to SessionDefaults.CookiePath (/ ). SameSite defaults to SameSiteMode.Lax (1 ). HttpOnly defaults to true . IsEssential defaults to false . |
IdleTimeout | The IdleTimeout indicates how long the session can be idle before its contents are abandoned. Each session access resets the timeout. This setting only applies to the content of the session, not the cookie. The default is 20 minutes. |
IOTimeout | The maximum amount of time allowed to load a session from the store or to commit it back to the store. This setting may only apply to asynchronous operations. This timeout can be disabled using InfiniteTimeSpan. The default is 1 minute. |
Session uses a cookie to track and identify requests from a single browser. By default, this cookie is named
.AspNetCore.Session
, and it uses a path of /
. Because the cookie default doesn't specify a domain, it isn't made available to the client-side script on the page (because HttpOnly defaults to true
).To override cookie session defaults, use
SessionOptions
:The app uses the IdleTimeout property to determine how long a session can be idle before its contents in the server's cache are abandoned. This property is independent of the cookie expiration. Each request that passes through the Session Middleware resets the timeout.
Session state is non-locking. If two requests simultaneously attempt to modify the contents of a session, the last request overrides the first.
Session
is implemented as a coherent session, which means that all the contents are stored together. When two requests seek to modify different session values, the last request may override session changes made by the first.Set and get Session values
Session state is accessed from a Razor Pages PageModel class or MVC Controller class with HttpContext.Session. This property is an ISession implementation.
The
ISession
implementation provides several extension methods to set and retrieve integer and string values. The extension methods are in the Microsoft.AspNetCore.Http namespace (add a using Microsoft.AspNetCore.Http;
statement to gain access to the extension methods) when the Microsoft.AspNetCore.Http.Extensions package is referenced by the project. Both packages are included in the Microsoft.AspNetCore.App metapackage.ISession
extension methods:The following example retrieves the session value for the
IndexModel.SessionKeyName
key (_Name
in the sample app) in a Razor Pages page:The following example shows how to set and get an integer and a string:
All session data must be serialized to enable a distributed cache scenario, even when using the in-memory cache. Minimal string and number serializers are provided (see the methods and extension methods of ISession). Complex types must be serialized by the user using another mechanism, such as JSON.
Add the following extension methods to set and get serializable objects:
State Management In Asp.net Mvc
The following example shows how to set and get a serializable object with the extension methods:
TempData
ASP.NET Core exposes the TempData property of a Razor Pages page model or TempData of an MVC controller. This property stores data until it's read. The Keep and Peek methods can be used to examine the data without deletion. TempData is particularly useful for redirection when data is required for more than a single request. TempData is implemented by TempData providers using either cookies or session state.
TempData providers
The cookie-based TempData provider is used by default to store TempData in cookies.
The cookie data is encrypted using IDataProtector, encoded with Base64UrlTextEncoder, then chunked. Because the cookie is chunked, the single cookie size limit found in ASP.NET Core 1.x doesn't apply. The cookie data isn't compressed because compressing encrypted data can lead to security problems such as the CRIME and BREACH attacks. For more information on the cookie-based TempData provider, see CookieTempDataProvider.
Choose a TempData provider
Choosing a TempData provider involves several considerations, such as:
- Does the app already use session state? If so, using the session state TempData provider has no additional cost to the app (aside from the size of the data).
- Does the app use TempData only sparingly for relatively small amounts of data (up to 500 bytes)? If so, the cookie TempData provider adds a small cost to each request that carries TempData. If not, the session state TempData provider can be beneficial to avoid round-tripping a large amount of data in each request until the TempData is consumed.
- Does the app run in a server farm on multiple servers? If so, there's no additional configuration required to use the cookie TempData provider outside of Data Protection (see ASP.NET Core Data Protection and Key storage providers).
Note
Most web clients (such as web browsers) enforce limits on the maximum size of each cookie, the total number of cookies, or both. When using the cookie TempData provider, verify the app won't exceed these limits. Consider the total size of the data. Account for increases in cookie size due to encryption and chunking.
Configure the TempData provider
The cookie-based TempData provider is enabled by default.
To enable the session-based TempData provider, use the AddSessionStateTempDataProvider extension method:
The order of middleware is important. In the preceding example, an
InvalidOperationException
exception occurs when UseSession
is invoked after UseMvc
. For more information, see Middleware Ordering.Important
If targeting .NET Framework and using the session-based TempData provider, add the Microsoft.AspNetCore.Session package to the project.
Query strings
A limited amount of data can be passed from one request to another by adding it to the new request's query string. This is useful for capturing state in a persistent manner that allows links with embedded state to be shared through email or social networks. Because URL query strings are public, never use query strings for sensitive data.
In addition to unintended sharing, including data in query strings can create opportunities for Cross-Site Request Forgery (CSRF) attacks, which can trick users into visiting malicious sites while authenticated. Attackers can then steal user data from the app or take malicious actions on behalf of the user. Any preserved app or session state must protect against CSRF attacks. For more information, see Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks.
Hidden fields
Data can be saved in hidden form fields and posted back on the next request. This is common in multi-page forms. Because the client can potentially tamper with the data, the app must always revalidate the data stored in hidden fields.
HttpContext.Items
The HttpContext.Items collection is used to store data while processing a single request. The collection's contents are discarded after a request is processed. The
Items
collection is often used to allow components or middleware to communicate when they operate at different points in time during a request and have no direct way to pass parameters.In the following example, middleware adds
isVerified
to the Items
collection.Later in the pipeline, another middleware can access the value of
isVerified
:For middleware that's only used by a single app,
string
keys are acceptable. Middleware shared between app instances should use unique object keys to avoid key collisions. The following example shows how to use a unique object key defined in a middleware class:Other code can access the value stored in
HttpContext.Items
using the key exposed by the middleware class:State Management In Asp.net Tutorial
This approach also has the advantage of eliminating the use of key strings in the code.
Cache
Caching is an efficient way to store and retrieve data. The app can control the lifetime of cached items.
Cached data isn't associated with a specific request, user, or session. Be careful not to cache user-specific data that may be retrieved by other users' requests.
For more information, see Response caching in ASP.NET Core.
Dependency Injection
Use Dependency Injection to make data available to all users:
- Define a service containing the data. For example, a class named
MyAppData
is defined: - Add the service class to
Startup.ConfigureServices
: - Consume the data service class:
Common errors
- 'Unable to resolve service for type 'Microsoft.Extensions.Caching.Distributed.IDistributedCache' while attempting to activate 'Microsoft.AspNetCore.Session.DistributedSessionStore'.'This is usually caused by failing to configure at least one
IDistributedCache
implementation. For more information, see Distributed caching in ASP.NET Core and Cache in-memory in ASP.NET Core. - In the event that the session middleware fails to persist a session (for example, if the backing store isn't available), the middleware logs the exception and the request continues normally. This leads to unpredictable behavior.For example, a user stores a shopping cart in session. The user adds an item to the cart but the commit fails. The app doesn't know about the failure so it reports to the user that the item was added to their cart, which isn't true.The recommended approach to check for errors is to call
await feature.Session.CommitAsync();
from app code when the app is done writing to the session.CommitAsync
throws an exception if the backing store is unavailable. IfCommitAsync
fails, the app can process the exception.LoadAsync
throws under the same conditions where the data store is unavailable.
Additional resources
(Redirected from ASP.NET state management)
Developer(s) | Microsoft |
---|---|
Initial release | January 5, 2002; 17 years ago |
Stable release | |
Written in | .NET languages |
Operating system | Microsoft Windows, Linux, macOS |
Type | Web framework |
License | Apache License 2.0 |
Website | asp.net |
Filename extension | .aspx , .cshtml , .vbhtml |
---|---|
Internet media type | text/html |
Developed by | Microsoft |
ASP.NET is an open-source[2]server-sideweb application framework designed for web development to produce dynamic web pages. It was developed by Microsoft to allow programmers to build dynamic web sites, web applications and web services.
It was first released in January 2002 with version 1.0 of the .NET Framework, and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code using any supported .NET language. The ASP.NET SOAP extension framework allows ASP.NET components to process SOAP messages.
ASP.NET's successor is ASP.NET Core. It is a re-implementation of ASP.NET as a modular web framework, together with other frameworks like Entity Framework. The new framework uses the new open-source .NET Compiler Platform (codename 'Roslyn') and is cross platform. ASP.NET MVC, ASP.NET Web API, and ASP.NET Web Pages (a platform using only Razor pages) have merged into a unified MVC 6.[3]
- 7References
Programming models[edit]
ASP.NET supports a number of programming models for building web applications:[4]
- ASP.NET Web Forms - a framework for building modular pages out of components, with UI events being processed server-side.
- ASP.NET MVC - allows for building web pages using the model–view–controller design pattern.
- ASP.NET Web Pages - a lightweight syntax for adding dynamic code and data access directly inside HTML markup.[5]
- ASP.NET Web API - a framework for building Web APIs on top of the .NET Framework.[6]
- ASP.NET WebHooks - implements the Webhook pattern for subscribing to and publishing events via HTTP.
- SignalR - a real-time communications framework for bi-directional communication between client and server.
Other ASP.NET extensions include:
- ASP.NET Handler: Are components that implement the
System.Web.IHttpHandler
interface. Unlike ASP.NET Pages, they have no HTML-markup file, no events and other supporting. All they have is a code-file (written in any .NET-compatible language) that writes some data to the server HTTP response. HTTP handlers are similar to ISAPI extensions. - ASP.NET AJAX: An extension with both client-side as well as server-side components for writing ASP.NET pages that incorporate Ajax functionality.
- ASP.NET Dynamic Data: A scaffolding extension to build data driven web applications
IIS integrated pipeline[edit]
On IIS 6.0 and lower, pages written using different versions of the ASP framework cannot share session state without the use of third-party libraries. This does not apply to ASP.NET and ASP applications running side by side on IIS 7. With IIS 7.0, modules may be run in an integrated pipeline that allows modules written in any language to be executed for any request.[7]
Development tools[edit]
Several available software packages exist for developing ASP.NET applications:
Software | Developer | Licensing |
---|---|---|
Visual Studio Code | Microsoft and community | Freeware open source |
Microsoft Visual Studio | Microsoft | Free and commercial |
Microsoft Visual Web Developer Express | Microsoft | Registerware |
CodeGear Delphi | Embarcadero Technologies | Commercial |
Macromedia HomeSite | Adobe Systems | Commercial |
Microsoft Expression Web | Microsoft | Free |
Microsoft SharePoint Designer | Microsoft | Free |
MonoDevelop | Xamarin and the Mono community | Free open source |
Adobe Dreamweaver | Adobe Systems | Commercial |
SharpDevelop | ICSharpCode Team | Free open source |
Rider | JetBrains | Proprietary |
Third-party frameworks[edit]
It is not essential to use the standard Web forms development model when developing with ASP.NET. Noteworthy frameworks designed for the platform include:
- Base One Foundation Component Library (BFC) is RAD framework for building .NET database and distributed computing applications.
- DotNetNuke is an open-source solution that provides both a web application framework and a content management system that allows for advanced extensibility through modules, skins, and providers.
- Castle MonoRail, an open-source MVC framework with an execution model similar to Ruby on Rails. The framework is commonly used with Castle ActiveRecord, an ORM layer built on NHibernate.
Versions[edit]
The ASP.NET releases history tightly correlates with the .NET Framework releases:
Date | Version | Remarks | New ASP.NET related features |
---|---|---|---|
January 16, 2002 | Old version, no longer supported: 1.0 | First version released together with Visual Studio .NET |
|
April 24, 2003 | Old version, no longer supported: 1.1 | released together with Windows Server 2003 released together with Visual Studio .NET 2003 |
|
November 7, 2005 | Old version, no longer supported: 2.0 | codename Whidbey released together with Visual Studio 2005 and Visual Web Developer Express and SQL Server 2005 |
|
November 21, 2006 | Old version, no longer supported: 3.0 |
| |
November 19, 2007 | Old version, no longer supported: 3.5 | Released with Visual Studio 2008 and Windows Server 2008 |
|
August 11, 2008 | Old version, no longer supported: 3.5 Service Pack 1 | Released with Visual Studio 2008 Service Pack 1 |
|
April 12, 2010 | Old version, no longer supported: 4.0 | Parallel extensions and other .NET Framework 4 features | The two new properties added in the Page class are MetaKeyword and MetaDescription. |
August 15, 2012 | Old version, no longer supported: 4.5 | Released with Visual Studio 2012 and Windows Server 2012 for Windows 8 Parallel extensions and other .NET Framework 4.5 features | |
October 17, 2013 | Old version, no longer supported: 4.5.1 | Released with Visual Studio 2013[8] for Windows Server 2012 R2 and Windows 8.1 |
|
May 5, 2014[9] | Older version, yet still supported: 4.5.2 |
| |
July 29, 2015[9] | Older version, yet still supported: 4.6 | Released[10] with Visual Studio 2015[11] and EF 7 Previews for Windows Server 2016 and Windows 10 |
|
November 30, 2015[9] | Older version, yet still supported: 4.6.1 | ||
August 2, 2016[9] | Older version, yet still supported: 4.6.2 |
| |
April 11, 2017[9] | Older version, yet still supported: 4.7 | Included in the Windows 10 Creators Update[12] |
|
October 17, 2017[9] | Current stable version:4.7.1 | Included in the Windows 10 Fall Creators Update.[13] |
|
November 18, 2015 | Old version, no longer supported: 5 RC1 | This version was later separated from ASP.NET and brought into a new project called ASP.NET Core, whose versioning started at 1.0.[14] | An entirely new project with different development tenets and goals |
Old version Latest version Future release |
Other implementations[edit]
The Mono Project supports 'everything in .NET 4.5 except WPF, WWF, and with limited WCF and limited ASP.NET 4.5 async stack.'[15] ASP.NET can be run with Mono using one of three options:- Apache hosting using the mod_mono module, FastCGI hosting, and XSP.
References[edit]
Citations[edit]
- ^'Announcing the .NET Framework 4.7.1'.
- ^'ASP.NET is part of a great open source .NET community'. Microsoft. May 14, 2013.
- ^'Introduction to ASP.NET 5 — ASP.NET 0.0.1 documentation'. asp.net.
- ^'Choose between ASP.NET and ASP.NET Core'. docs.microsoft.com.
- ^'ASP.NET Web Pages (Razor) FAQ'. docs.microsoft.com.
- ^'Get Started with ASP.NET Web API 2 (C#)'. docs.microsoft.com.
- ^'How to Take Advantage of the IIS 7.0 Integrated Pipeline'. iis.net.
- ^'Announcing release of ASP.NET and Web Tools for Visual Studio 2013'.
- ^ abcdef'.net framework product lifecycle'.
- ^'Announcing .NET Framework 4.6'.
- ^'Visual Studio 2015 and Visual Studio 2013 Update 5 Released'. msdn.com. Microsoft.
- ^'Announcing the .NET Framework 4.7'.
- ^'Announcing the .NET Framework 4.7.1'.
- ^'Releases'. GitHub.
- ^'Compatibility | Mono'. Compatibility | Mono. 8 September 2015. Archived from the original on 2 July 2016. Retrieved 29 August 2016.
Sources[edit]
- MacDonald, Matthew; Szpuszta, Mario (2005). Pro ASP.NET 2.0 in C# 2005 (1st ed.). Apress. ISBN1-59059-496-7.
External links[edit]
Wikibooks has more on the topic of: ASP.NET |
- ASP.NET at Curlie
- ASP.NET on MSDN
Retrieved from 'https://en.wikipedia.org/w/index.php?title=ASP.NET&oldid=898410065#State_management'