Getting a MIME type from a file extension in ASP.NET 4.5
If you’ve ever implemented a file upload or download scenario in ASP.NET, you’ve likely come across the situation of having to provide a MIME type based off of a file extension. IIS does this automatically when it serves files, but it seems like in ASP.NET there isn’t a good way to provide this functionality. Searches on the web might point you to building your own Dictionary of MIME types or just writing a switch statement, but this felt like a hack to me and so I turned to a resident expert, Levi Broderick.
It turns out in ASP.NET 4.5 we shipped a little-known new type, System.Web.MimeMapping, which has an API called GetMimeMapping(string fileName). Here is the MSDN documentation. You can pass either a file name as the method implies, or an extension.
This is awesome. It turns what would have been a pain into a one line call. But how is it implemented – did the ASP.NET team just do the “hack” for you by building a table?
The answer is yes and no. If you are running IIS in classic mode, the fallback is indeed a Dictionary of over 300 mappings of file extensions to MIME types. However, if you are running in integrated pipeline mode (most people), the list of MIME types used by the API is actually the list in IIS. This means that as you upgrade Windows and more MIME types are added to IIS, the code you write doesn’t need to be updated to take advantage of the changes.
Hope this hidden gem helps!
Update: As folks have mentioned in the comments, this should not be the only check you run on a file upload, but it does simply the development step of generating the MIME type mapping once you have verified that you have the correct file type by checking bytes, for security reasons.