Set the ASP.NET Application Object to Read-Only
Requirement:
Pre-Load the ASP.NET Application object and dont 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.
About Newsletter
Comments are closed.