ASP.NET/IIS6:如何搜索服务器的mime映射?

Ian*_*oyd 11 asp.net iis mime mime-types

我想从代码隐藏文件中找到IIS ASP.NET Web服务器上给定文件扩展名的mime类型.

我想搜索服务器本身在提供文件时使用的相同列表.这意味着将包含Web服务器管理员添加到Mime Map的任何mime类型.

我可以盲目地使用

HKEY_CLASSES_ROOT\MIME\Database\Content Type
Run Code Online (Sandbox Code Playgroud)

但是没有记录为IIS使用的列表,也没有记录存储Mime Map的位置.

我可以盲目地调用FindMimeFromData,但是没有记录为IIS使用的相同列表,也不能保证IIS Mime Map也将从该调用返回.

Goy*_*uix 12

这是另一个类似的实现,但不需要添加COM引用 - 它通过反射检索属性,并将它们存储在NameValueCollection中以便于查找:

using System.Collections.Specialized; //NameValueCollection
using System.DirectoryServices; //DirectoryEntry, PropertyValueCollection
using System.Reflection; //BindingFlags

NameValueCollection map = new NameValueCollection();
using (DirectoryEntry entry = new DirectoryEntry("IIS://localhost/MimeMap"))
{
  PropertyValueCollection properties = entry.Properties["MimeMap"];
  Type t = properties[0].GetType();

  foreach (object property in properties)
  {
    BindingFlags f = BindingFlags.GetProperty;
    string ext = t.InvokeMember("Extension", f, null, property, null) as String;
    string mime = t.InvokeMember("MimeType", f, null, property, null) as String;
    map.Add(ext, mime);
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以非常轻松地缓存该查找表,然后再引用它:

Response.ContentType = map[ext] ?? "binary/octet-stream";
Run Code Online (Sandbox Code Playgroud)

  • 这似乎不适用于IIS Express - 您将获得"System.Runtime.InteropServices.COMException(0x80070005):访问被拒绝." 访问entry.Properties ["MimeMap"]时. (4认同)

Kev*_*Kev 10

这是我之前制作的一个:

public static string GetMimeTypeFromExtension(string extension)
{
    using (DirectoryEntry mimeMap = 
           new DirectoryEntry("IIS://Localhost/MimeMap"))
    {
        PropertyValueCollection propValues = mimeMap.Properties["MimeMap"];

        foreach (object value in propValues)
        {
            IISOle.IISMimeType mimeType = (IISOle.IISMimeType)value;

            if (extension == mimeType.Extension)
            {
                return mimeType.MimeType;
            }
        }

        return null;

    }
}
Run Code Online (Sandbox Code Playgroud)

在COM选项卡下添加对引用System.DirectoryServices和引用Active DS IIS Namespace Provider.扩展需要有前导点,即.flv.