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

前端 未结 5 2069
醉话见心
醉话见心 2020-12-15 01:06

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 ba

5条回答
  •  忘掉有多难
    2020-12-15 01:54

    I had a similar problem a few month ago and solved it with this simple wrapper-class around System.Web.MimeMapping (as mentioned by Richard Szalay):

    /// 
    /// This class allows access to the internal MimeMapping-Class in System.Web
    /// 
    class MimeMappingWrapper
    {
        static MethodInfo getMimeMappingMethod;
    
        static MimeMappingWrapper() {
            // dirty trick - Assembly.LoadWIthPartialName has been deprecated
            Assembly ass = Assembly.LoadWithPartialName("System.Web");
            Type t = ass.GetType("System.Web.MimeMapping");
    
            getMimeMappingMethod = t.GetMethod("GetMimeMapping", BindingFlags.Static | BindingFlags.NonPublic);
        }
    
        /// 
        /// Returns a MIME type depending on the passed files extension
        /// 
        /// File to get a MIME type for
        /// MIME type according to the files extension
        public static string GetMimeMapping(string fileName) {
            return (string)getMimeMappingMethod.Invoke(null, new[] { fileName });
        }
    }
    

提交回复
热议问题