2010-08-03 71 views
1

在我的應用程序中,我有一個區域調用Mobile。在這個區域我有一個文件夾調用資產,我們放置所有的CSS,JavaScript和圖像。無法在ASP.NET MVC 2中使用相對路徑和區域

訪問視圖工作得很好。 http://localhost/webapp/mobile/stuff

問題是當我訪問我的CSS,JavaScript和圖像。

在我看來,我不能這樣做。

<img src="Assets/css/styles.css" /> 

的原因是因爲真正的網址是:http://localhost/webapp/areas/mobile/assets/css/styles.css

有沒有一種方法來映射http://localhost/webapp/areas/mobilehttp://localhost/webapp/mobile對靜態文件?

感謝, 蘭德爾

回答

3

我想出的解決方案是使用一個簡單的IHTTPModule,它會爲我重寫url。以下是我爲BeginRequest事件實施的方法。

void BeginRequest(object sender, EventArgs e) 
{ 
    var context = HttpContext.Current; 
    var path = context.Request.Path; 

    // Add Areas to the Mobile path, so we don't have to specify it manually. 
    // This is mainly for handling static resources that you place in areas. 
    if (!path.Contains("Mobile/")) return; 
    if (path.EndsWith(".png") || 
     path.EndsWith(".gif") || 
     path.EndsWith(".css") || 
     path.EndsWith(".js") || 
     path.EndsWith(".htm") || 
     path.EndsWith(".cache")) 
     context.RewritePath(path.Replace("Mobile/", "Areas/Mobile/")); 
} 
1

你可能需要做這樣的事情:

<img src="../../Mobile/Assets/css/styles.css" /> 

...取決於您的當前目錄實際上是。您也可以嘗試這樣的:

<img src="~Mobile/Assets/css/styles.css" /> 

的一個好辦法找出實際的路徑應是從Project Explorer拖動資產(在這種情況下Styles.css中)到您的視圖,並讓視覺工作室爲您創建路徑。