Scott Hanselman

Set the ASP.NET Application Object to Read-Only

January 10, 2003 Comment on this post [0] Posted in Web Services | ASP.NET
Sponsored By

Requirement:

Pre-Load the ASP.NET Application object and don’t allow other pages in your project to add/modify/delete. Basically, make Application read-only.

Solution:

         private void SetApplicationReadOnlyStatus( bool state ) {
                  Type type = Application.GetType().BaseType;
                  PropertyInfo readPropInfo = type.GetProperty("IsReadOnly",  BindingFlags.NonPublic | BindingFlags.Instance) ;
                  if( readPropInfo != null ) {
                        readPropInfo.SetValue( Application,Convert.ChangeType(state,readPropInfo.PropertyType ) ,null);
                  }
            }
            private void Page_Load(object sender, System.EventArgs e) {
                  Application["MyKey"] = "myValue";
                  // Set application to readonly so that we will not allow any changes.
                  SetApplicationReadOnlyStatus( true );
                  try
                  {
                        // Try setting a value 
                        Application["MyKey"] = "New value";
                        Response.Write("You won't see this");
                  }
                  catch(Exception ex) {
                        // You'll end up here
                        Response.Write(ex.Message);
                }
            }

Thanks to Sairama for the code!

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.