Optimize ASP.NET Performance with View State Caching
Optimize ASP.NET Performance with View State Caching
Join the DZone community and get the full member experience.Join For Free
Maintain Application Performance with real-time monitoring and instrumentation for any application. Learn More!
ASP.NET View State is a very powerful feature of ASP.NET that provides a client side state management mechanism. It helps preserve page and control values between complete round trips for client requests. This gives a state full programming capability over a stateless protocol such as HTTP.
ASP.NET View State is stored in a hidden field on the page as an encoded Base64 string, as part of every response sent to the client and is also returned to the server by the client as part of a post back.
<input id="__VIEWSTATE" type="hidden" name="__VIEWSTATE" value="/wEPDwUJNzg0MDMxMDA1D2QWAmYPZBYCZg9kFgQCAQ9kFgICBQ9kFgJmD2QWAgIBDxYCHhNQ cm2aW91c0NvbnRyb2xNb2RlCymIAU1pY3Jvc29mdC5TaGFyZVBvaW50LldlYkNvbnRyb2xzLlNQQ29u dHJbE1vZGUsIE1pY3Jvc29mdC5TaGFyZVBvaW50LCBWZXJzaW9uPTEyLjAuMC4wLCBDdWx0dXJlPW5l dXRyWwsIFB1YmxpY0tleVRva2VuPTcxZTliY2UxMTFlOTQyOWMBZAIDD2QWDgIBD2QWBgUmZ19lMzI3 YTQwMF83ZDA1XzRlMjJfODM3Y19kOWQ1ZTc2YmY1M2IPD2RkZAUmZ18yNDQ3NmI4YV8xY2FlXzRmYTV fOTkxNl8xYjIyZGYwNmMzZTQPZBYCZg8PZBYCHgVjbGFzcwUbbXMtc2J0YWJsZWFsdCBtcy1zYnRhYm xFlOTQyOWMBZAIDD2YjIyZGYjIyZGYjIyZGlYkNvbnRyb2xzLlNQQ29YkNvbnRyb2xzLlNQQ2UxMTFl OTQyOWMBZAIDD2QWDgIBD2QWBgUmZ19lMzI3YTQwMF83ZDA1XzRlMjJfODM3Y19kOWQ1ZTc2YmY1M2IPD...==" />
Problems with ASP.NET View State
ASP.NET View State does come with a few issues that you need to understand and resolve. Once you resolve these issues, you are able to benefit from ASP.NET View State without any problems. They are discussed below.
1. ASP.NET View State is often heavy
First of all, in many situations, ASP.NET View State becomes very large especially when your ASP.NET application has a lot of rich and heavy controls and widgets on its pages. This results in a lot of data traveling back and forth between your browser and the web server.
Due to this heavy payload, your ASP.NET performance drops because your pages are taking longer to respond. This is probably the most visible change you see in your ASP.NET application.
Another impact is the extra bandwidth consumption. This has a financial cost associated with it because you’re paying for the bandwidth and if an average ASP.NET View State ends up in 100’s of kilobytes, this could easily consume a lot of bandwidth when millions of requests are processed.
2. ASP.NET View State is a security risk
ASP.NET View State can also pose a security risk when sending confidential data as part of view state to client. This data is vulnerable to attacks and can be tempered by an attacker which is a serious security threat. You can encrypt the ASP.NET View State data but this is again going to have a performance cost to it.
Solution to ASP.NET View State Problems
One way you can resolve ASP.NET View State issues is by storing the actual ASP.NET View State on the Web server and sending a unique token (or ID) in place of it to the browser so the browser can send this token back to the web server next time. The web server then uses this token to find the right ASP.NET View State in its store.
You can do this because the ASP.NET View State encoded string is never used by the browser and is always returned to the web server. So, whether it is an encoded string or a token is the same for the browser. Below is an example of a token being used in place of ASP.NET View State.
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="vs:cf8c8d3927ad4c1a84da7f891bb89185" />
But, if your ASP.NET application is running in a load balanced web farm, the next HTTP request might come to another web server. Therefore, you must store the ASP.NET View State in a shared store that is accessible from all the web servers.
The best place to store ASP.NET View State on the server is in a distributed cache. This way, not only can you have a common store for all web servers, but you also have an extremely fast and scalable in-memory store as compared to SQL Server database or other storage options.
NCache is an extremely fast and scalable distributed cache for .NET. It also lets you store ASP.NET View State to solve the issues described above.
How to use NCache for ASP.NET View State Caching?
NCache allows you to cache ASP.NET View State without any code changes to your ASP.NET application. You need to follow the steps mentioned below to configure NCache for caching your ASP.NET View State.
Step 1: Create an app.browser file in App_browsers directory. Plug in page adapters in the app.browser file as follows:
File: App_browsers\app.browser <browser refID="Default"> <controlAdapters> <adapter controlType="System.Web.UI.Page" adapterType="Alachisoft.NCache.Adapters.PageAdapter" /> </controlAdapters> </browser>
Step 2: Add the following assembly reference in compilation section of web.config file:
File: web.config <compilation defaultLanguage="c#" debug="true" targetFramework="4.0"> <assemblies> <add assembly="Alachisoft.NCache.Adapters, Version=220.127.116.11, Culture=neutral, PublicKeyToken=CFF5926ED6A53769"/> </assemblies> </compilation>
Step 3: Register NCache config section in your web.config file.
File: web.config <configSections> <sectionGroup name="ncContentOptimization"> <section name="settings" type="Alachisoft.NCache.ContentOptimization.Configurations.ContentSettings" allowLocation="true" allowDefinition="Everywhere"/> </sectionGroup> </configSections>
Step 4: Specify settings for your config section in web.config file (that was registered above). These settings control NCache ASP.NET View State Caching features.
File: web.config <ncContentOptimization> <settings viewstateThreshold="12" enableViewstateCaching="true" enableTrace="false" groupedViewStateWithSessions="false"> <cacheSettings cacheName="myCache" maxViewStatesPerSession="3"> <expirationtype="Absolute" duration="1" /> </cacheSettings> </settings> </ncContentOptimization>
Step 5: In the end, register the HTTP handler in the HttpHandlers section of web.config as following:
File: web.config <httphandlers> <add verb="GET,HEAD" path="NCResource.axd" validate="false" type="Alachisoft.NCache.Adapters.ContentOptimization.ResourceHandler, Alachisoft.NCache.Adapters, Version=18.104.22.168, Culture=neutral, PublicKeyToken=cff5926ed6a53769"/> </httphandlers>
Benefits of Caching ASP.NET View State on the Server
You gain the following benefits by caching your ASP.NET View State in NCache.
- Improve ASP.NET Performance: A small token is now sent to the browser instead of 100’s of kilobytes of View State data. This reduces the payload size and improves performance.
- Reduce Bandwidth Cost: Smaller payload also means a significant reduction in bandwidth consumption cost. This could save you a lot of money.
- Security: Now that ASP.NET View State encoded string is not sent to the browser, there is no longer any security risks.
- Fast & Scalable ASP.NET View State Storage: NCache is an extremely fast and scalable distributed cache. This means your ASP.NET never faces any scalability bottlenecks due to ASP.NET View State storage.
- ASP.NET View State Reliability thru Replication: NCache replicates all data in the distributed cache intelligently. This means you don’t lose any ASP.NET View State even if a cache server goes down.
Advanced ASP.NET View State Caching Features in NCache
NCache provides you a rich set of features for caching and managing ASP.NET View State. Below is a list of them.
- Minimum size threshold: NCache allows you to specify a minimum size of ASP.NET View State. Any View State smaller than this is not cached. This enables you to only cache heavy View State.
- Link ASP.NET View State with Session State: You can link an ASP.NET View State with your Session State. This way, when the user session expires, all his view states are automatically removed from the cache.
- Page level max count threshold: You can configure how many view states should be kept for a given page in a FIFO manner. This way, the oldest view state is removed whenever a new view state is created for this page. This optimizes your memory consumption in the cache server by not caching view states that you would never need.
- Session level max count threshold: Similar to page level, you can specify maximum view state count for a user session in a FIFO manner. This way, the oldest view state is removed whenever a new view state is created.
- Page level and session level settings: You can specify all of the above settings differently for each page or keep them common to all sessions.
As you have seen, caching ASP.NET View State on the server provides you a lot of benefits and improves your ASP.NET performance significantly. It also saves you a lot of money in bandwidth consumption costs. And, on top of all this, it helps with some security issues related to ASP.NET View State traveling from the web server to your browser.
I encourage you to take a look at your application and if your application contains ASP.NET View State then try to cache it on the server side. And, take a look at NCache for this purpose. You can find out more about NCache at http://www.alachisoft.com
Opinions expressed by DZone contributors are their own.