How can I query IIS for MIME Type Mappings?

2019-01-23 17:30发布

问题:

How can I programatically read IIS's MIME types? I'd like to use them when I stream data to my clients using WCF.

Any tips, or API would be appreciated

回答1:

I'm making the assumption this is IIS7 only and you're using C#3.0 or later:

using Microsoft.Web.Administration;
....
using(ServerManager serverManager = new ServerManager())
{
  // If interested in global mimeMap:
  var config = serverManager.GetApplicationHostConfiguration();

  // Use if interested in just a particular site's mimeMap:
  // var config = serverManager.GetWebConfiguration("Default Web Site");

  var staticContent = config.GetSection("system.webServer/staticContent");
  var mimeMap = staticContent.GetCollection();

  // Print all mime types
  foreach (var mimeType in mimeMap)
  {
    Console.WriteLine(String.Format("{0} = {1}", mimeType["fileExtension"],
         mimeType["mimeType"]));
  }

  // Find a mime type based on file extension
  var mt = mimeMap.Where(
        a => (string) a.Attributes["fileExtension"].Value == ".pdf"
      ).FirstOrDefault();

  if (mt != null)
  {
    Console.WriteLine("Mime type for .pdf is: " + mt["mimeType"]);
  }
}

You need to reference the Microsoft.Web.Administration.dll in c:\windows\system32\inetsrv.

Your code also needs Administrator rights to be able to do this as well.



回答2:

If using ASP.Net 4.5 or higher, you can use System.Web.MimeMapping.GetMimeMapping as follows:

void Page_Init()
{
    string[] extensions = new string[]
    {
        ".pdf",
        ".xls",
        ".xlsx",
        ".ppt",
        ".pptx",
        ".mp3",
        ".ogg",
        ".svg",
        ".pdf",
        ".png",
    };

    foreach (string extension in extensions)
    {
        string mimeType = MimeMapping.GetMimeMapping(extension);
        Response.Write(String.Format("{0} => {1}<br />",
                extension,
                mimeType
            ));
    }
}

Result:

.pdf => application/pdf
.xls => application/vnd.ms-excel
.xlsx => application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.ppt => application/vnd.ms-powerpoint
.pptx => application/vnd.openxmlformats-officedocument.presentationml.presentation
.mp3 => audio/mpeg
.ogg => video/ogg
.svg => image/svg+xml
.pdf => application/pdf
.png => image/png


回答3:

Mime types registered to the system are defined in the registry under "HKEY_CLASSES_ROOT\Mime\Database\Content Type".

Are you looking for mime types for a particular web site that is defined in IIS?



回答4:

As an alternative to reading the registry, or lowering security on the config directory, there is a pre-populated MIME database within the HTML Agility Pack