State management in ASP.NET MVC

State management in ASP.NET MVC is an interesting throwback to the core concept of statelessness in HTTP—wherein there is no default support for state persistence. Compare this to ASP.NET Web Forms, which by default use ViewState to store the state for each control.

There are many benefits associated with stateless pages, or when state is maintained only on the client browser, via a cookie for example:
  • Sites can easily scale to a cluster of servers in a server farm without having to worry about maintaining session state.
  • Debugging problems produced by session expiry will not be an issue.
  • Cached pages can be put to better use, as most of the page content might stay the same in the absence of session state.
  • A session is easy to recover if the server crashes when state is persisted on the client rather than the server.
The MVC team clearly had the above in mind when creating a default, stateless architecture.

Though there is no default support for state persistence in MVC, developers can use several options to enable state persistence across page post-backs:
  • Session state
  • ASP.NET cache
  • Cookies
Each of the above has its own pros and cons depending on the scale of the deployment. By letting developers build their own persistence logic, ASP.NET MVC encourages developers to follow best practices in ensuring minimal memory and bandwidth usage which has been sorely lacking in Web Forms considering the common abuse of ViewState for caching large, unnecessary information.

No comments:

Post a Comment