Geeks With Blogs
The Quandary Phase This code was generated by a tool.

An interesting question arose today of how to read property values from the HttpContext class dynamically.

It is easy to imagine why this would be useful. For example, you might want to store a number of property names in a configuration file, and retrieve these values on-the-fly, perhaps for logging purposes.

The first thing to notice about the HttpContext class is that it manages its own instances. What I mean by this is the class contains a public static property named 'Current' which returns a reference to the HttpContext instance for the current thread. This is similar to the singleton pattern, but in this case managing an instance per thread, rather than a single instance for the app domain.

So the first thing which needs to be accomplished is getting a reference to the current HTTP context. Doing so is not quite as straightforward as a plain old GetType() call, however, as the HttpContext class lives in the System.Web dll. GetType() only searches the current assembly and .NET Framework mscorlib by default, any other assembly must be explicitly named.

For example:

string path = "System.Web.HttpContext";
string assembly = "System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
string contextPath = "Current";
 
Type typ = Type.GetType(path + ", " + assembly, true, true);
PropertyInfo prop = null;
 
//get the HTTP context property info
prop = typ.GetProperty(contextPath, (BindingFlags.Public | BindingFlags.Static));
 
//get a reference to the current HTTP context
object context = prop.GetValue(null, null);

 

The code above declares a string containing the namespace-qualified name of the HttpCOntext class, and another string containing the full display name for the System.Web assembly, then comma-delimits and concatenates these, and passes the resulting string to the Type.GetType() method. Of course, in the real world, you would not want to hard-code either of these values: both the class name and assembly name would be better read from a configuration file.

Now you have a reference to the current HTTP context, the rest is pretty straightforward. All that's left to do is extract the property value using the PropertyInfo.GetValue() method:

if (context != null)
{
    //get the property info for the specified property
    prop = context.GetType().GetProperty("IsDebuggingEnabled", (BindingFlags.Public | BindingFlags.Instance));
 
    //get the property value
    object propertyValue = prop.GetValue(context, null);
}

 

The code above retrieves the boolean IsDebuggingEnabled property value, but now we have all the ingredients to wrap this up as a more useful method:

/// <summary>
/// Extracts the value of the specified property from the current HTTP context.
/// </summary>
/// <typeparam name="T">The return type for the property value.</typeparam>
/// <param name="propertyName">The property name.</param>
/// <returns></returns>
public T GetHttpContextPropertyValue<T>(string propertyName)
{
 
    object propertyValue = null;
 
    string path = "System.Web.HttpContext";
    string assembly = "System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";
    string contextPath = "Current";
 
    Type typ = Type.GetType(path + ", " + assembly, true, true);
    PropertyInfo prop = null;
 
    //get the HTTP context property info
    prop = typ.GetProperty(contextPath, (BindingFlags.Public | BindingFlags.Static));
 
    //get a reference to the current HTTP context
    object context = prop.GetValue(null, null);
 
    if (context != null)
    {
        //get the property info for the specified property
        prop = context.GetType().GetProperty(propertyName, (BindingFlags.Public | BindingFlags.Instance));
 
        //get the property value
        propertyValue = prop.GetValue(context, null);
    }
 
    //return the value as type T
    return (T)propertyValue;
}
 
private void TestGetHttpContextPropertyValue()
{
    //call the method...
    bool b = this.GetHttpContextPropertyValue<bool>("IsDebuggingEnabled");
}

 

And now we have a method which dynamically returns the value of any property within the current HTTP context, using generics to strongly type the return value.

Posted on Wednesday, October 22, 2008 4:57 PM | Back to top


Comments on this post: Using Reflection To Extract Values From a Static Class

# re: Using Reflection To Extract Values From a Static Class
Requesting Gravatar...
The added inshight increases my insights about:Indonesian Furniture
Left by Indonesian Teak Garden Furniture on Dec 07, 2010 5:26 AM

# re: Using Reflection To Extract Values From a Static Class
Requesting Gravatar...
Once again great post. You seem to have a good understanding of these themes.When I entering your blog,I felt this . Come on and keep writting your blog will be more attractive. To Your Success!
Left by Choline Chloride suppliers on Jan 05, 2011 7:35 PM

# re: Using Reflection To Extract Values From a Static Class
Requesting Gravatar...
The first thing to notice about the HttpContext class is that it manages its own instances. What I mean by this is the class contains a public static property
Left by Alpha lipoic acid on Jan 05, 2011 7:37 PM

Comments have been closed on this topic.
Copyright © Adam Pooler | Powered by: GeeksWithBlogs.net