Search code examples
.netmime-types

Add custom MIME type in System.Web.MimeMapping programmatically


I am using MimeMapping class from System.Web assembly to get mime types from file extensions.

But in case of .HEIC extensions it is returning mime type as application/octet-stream. But the original mime type associated with this extension is image/heic.

MimeMapping.GetMimeMapping("something.HEIC")//returning application/octet-stream

Do MimeMapping class provides any api to add new mappings so that I can get the correct mime-type?


Solution

  • Thanks to the tip by Rup and reflection. I'd created a method which can be used to add custom mime-types to the private static variable which MimeMapping class uses for resolving mime types.

            public static void RegisterMimeTypes(IDictionary<string, string> mimeTypes)
            {
                if (mimeTypes == null || mimeTypes.Count == 0)
                    return;
                var field = typeof(System.Web.MimeMapping).GetField("_mappingDictionary",
                            System.Reflection.BindingFlags.NonPublic |
                            System.Reflection.BindingFlags.Static);
    
                var currentValues = field.GetValue(null);
                var add = field.FieldType.GetMethod("AddMapping",
                          System.Reflection.BindingFlags.NonPublic |
                          System.Reflection.BindingFlags.Instance);
    
                foreach (var mime in mimeTypes)
                {
                    add.Invoke(currentValues, new object[] { mime.Key, mime.Value });
                }
    
            }
    

    Now you can register your list of custom mime-types on the application startup like below

        var mimeTypes = new Dictionary<string, string>()
        {
            { ".heic", "image/heic"},
            {".extn", "custom/mime" }
        };
    
        RegisterMimeTypes(mimeTypes);
    

    Example

    MimeMapping.GetMimeMapping("filename.heic")// will return image/heic