A Better MIME Mapping Stealer!

In the interest of self-improvement and sharing knowledge, I felt that I should share an update to my last post. I discovered a slightly better way to create the GetMimeMapping delegate/method via reflection that involves less casting and overhead, and is more Object Oriented in a sense. It allows the signature of the reflected method to be Func<string, string> instead of MethodInfo. Code below, note the use of Delegate.CreateDelegate(Type, MethodInfo):

/// <summary>
/// Exposes the Mime Mapping method that Microsoft hid from us.
/// </summary>
public static class MimeMappingStealer
{
    // The get mime mapping method
    private static readonly Func<string, string> _getMimeMappingMethod = null;
/// &lt;summary&gt;
/// Static constructor sets up reflection.
/// &lt;/summary&gt;
static MimeMappingStealer()
{
    // Load hidden mime mapping class and method from System.Web
    var assembly = Assembly.GetAssembly(typeof(HttpApplication));
    Type mimeMappingType = assembly.GetType(&quot;System.Web.MimeMapping&quot;);
    _getMimeMappingMethod = 
	    (Func&lt;string, string&gt;)Delegate.CreateDelegate(typeof(Func&lt;string, string&gt;), 
		    mimeMappingType.GetMethod(&quot;GetMimeMapping&quot;, 
            BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public |
            BindingFlags.NonPublic | BindingFlags.FlattenHierarchy));
}

/// &lt;summary&gt;
/// Exposes the hidden Mime mapping method.
/// &lt;/summary&gt;
/// &lt;param name=&quot;fileName&quot;&gt;The file name.&lt;/param&gt;
/// &lt;returns&gt;The mime mapping.&lt;/returns&gt;
public static string GetMimeMapping(string fileName)
{
    return _getMimeMappingMethod(fileName);
}

}

One minute to read

Determine MIME Type from File Name

I recently had a need, in an ASP.NET MVC3 application, to read raw HTML, CSS, JS, and image files from disk and return them to the user… A sort of “pass-through” if you will. Normally I’d have simply routed to a custom HTTP handler per file type or just allowed MVC3 to map existing files to supply its own .NET HTTP handlers and do all of this work for me, but in this case I needed the mapped “directory” to switch behind the scenes based on Session settings… So I ultimately had to feed these files through a Controller and Action Method to gain access to the Session.
4 minutes to read