How do I get the MIME type of a file being requested in ASP.NET C#?

mkelley33 picture mkelley33 · Aug 19, 2009 · Viewed 9.6k times · Source

I would like to handle requests differently depending upon the MIME type. For example, I have PDF's, images and other media files that I would like to prohibit access to based on their respective MIME types. Any ideas on how to do this? Thanks for the help.

I should also note that accessing the Windows registry is not an option for my application.

Answer

Richard Szalay picture Richard Szalay · Aug 19, 2009

.NET's mime-type mappings are stored in the System.Web.MimeMapping class which offers the GetMimeMapping method.

Prior to .NET 4.5, this class was marked as internal, and thus not available to your code. In that case the best you can do is steal the list, which you can get using Reflector and decompile the static constructor (cctor).

If taking that approach, you may be better off simply creating a list of supported extensions and their mime type and storing it on a dictionary. (The list inside MimeMapping is a tad verbose)