2

我在另一个目录中有一些 html 文件,其中包含一些 javascript、图像和 css。我想在我的站点中使用该文件并限制用户访问该 index.html 链接。我在控制器操作中使用了 return File 方法,但它无法打开该目录上的图像,因此它不起作用。什么是正确的解决方案?你有什么想法吗?

附言。(当我调试代码时,我看到 js、css 和 html 文件可以使用正确的 mime 类型打开,除了 jpg 或 png 文件)

public ActionResult User(string name)
{
     string file = (Server.MapPath(Url.Content("~/Content/Users/" + name)));
     string path = Path.Combine(file);
     string mime = GetMimeType(path);
     return File(path, mime);
}



public string GetMimeType(string fileName)
 {
     string mimeType = "application/unknown";
     string ext = Path.GetExtension(fileName).ToLower();
     Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); 
     if (regKey != null && regKey.GetValue("Content Type") != null)
      {
        mimeType = regKey.GetValue("Content Type").ToString();
      }
     return mimeType;
 }
4

2 回答 2

0

确保在调试过程中将以下值返回给图像扩展:

.jpg/.jpeg => mime type: image/jpeg, 
 .png => mime type:image/png

您可以使用 xml 文件,其中每个文件扩展名都映射到其 mime 类型。这将确保您的系统可以处理所有可能的扩展。链接有一个建议的 xml 文件

于 2012-12-14T17:44:39.377 回答
0

最好只为静态内容 mime 类型查询 IIS。这样,您就有了一个管理它们的位置。

using Microsoft.Web.Administration;
//--- stuff goes on ---//


ServerManager serverManager = new ServerManager();
var config = serverManager.GetApplicationHostConfiguration();
var staticContent = config.GetSection("system.webServer/staticContent");
var mimeMap = staticContent.GetCollection();
var mType =mimeMap.FirstOrDefault(a => (string) a.Attributes["fileExtension"].Value == ".pdf");
return (mType == null) ? "text/plain" : mType["mimeType"];
于 2012-12-14T21:17:11.183 回答