2012-11-28 31 views
2

我在一些javascripts,圖像和css的另一個目錄中有一些html文件。我想在我的網站中使用這些文件並限制用戶訪問該index.html鏈接。我在控制器操作中使用了返回File方法,但無法在該目錄上打開圖像,因此無法正常工作。什麼是適當的解決方案?你有想法嗎?如何從mvc中的另一個目錄中打開html文件

ps。 (當我調試的代碼,我看到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; 
} 

回答

0

確保在調試過程中的下列值返回到圖像擴展:

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

您可以使用一個xml文件,其中每個文件擴展名映射到它的MIME類型。這將確保您的系統可以處理所有可能的擴展。 This鏈接有一個建議的xml文件

0

更好的只是qyery靜態內容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"]; 
相關問題