2009-06-03 14 views
2

我有一個使用主題的ASP.NET應用程序。假設我有一個名爲「MySkin」的主題。ASP.NET - 主題和相對引用

我有一個頁面位於我的應用程序的子目錄中。當我引用一個使用「MySkin」的頁面時,我注意到ASP.NET呈現了一個鏈接元素,它走到了網站的根目錄,然後進入了App_Themes目錄。下面是一個例子鏈接元素我在呈現ASP.NET頁面發現:

<link href="../../App_Themes/MySkin/theme.css" type="text/css" rel="stylesheet" /> 

是否有一個原因,呈現鏈接元素不使用,而不是執行以下操作:

<link href="/App_Themes/MySkin/theme.css" type="text/css" rel="stylesheet" /> 

這是一個瀏覽器兼容性問題還是還有其他原因?

我問的原因是因爲我使用Server.Execute呈現我的ASP.NET頁面並將結果存儲在不同的目錄中。因此,我寧願使用第二種方式來引用我的主題的CSS。

謝謝!

回答

0

根據內置的內部類PageThemeBuildProvider,asp.net CSS文件的創建相對路徑包括在主題目錄

internal void AddCssFile(VirtualPath virtualPath) 
{ 
    if (this._cssFileList == null) 
    { 
     this._cssFileList = new ArrayList(); 
    } 
    this._cssFileList.Add(virtualPath.AppRelativeVirtualPathString); 
} 

爲了解決你的問題,你可以嘗試使用基本標籤:

//Add base tag which specifies a base URL for all relative URLs on a page 
System.Web.UI.HtmlControls.HtmlGenericControl g = new System.Web.UI.HtmlControls.HtmlGenericControl("base"); 
//Get app root url 
string AppRoot = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, ""); 
g.Attributes.Add("href",AppRoot); 
Page.Header.Controls.AddAt(0,g); 

使用這種方法的壞處是,如果應用程序URL被更改,鏈接將會中斷。

爲了儘量減少這種變化的影響,你可以使用HTML包括代替基本標記,包括包含您的基本標記如下文件:

base.html文件包含:

<base href="http://localhost:50897"></base> 

這可能在應用程序創建開始請求:

bool writeBase = true; 
     protected void Application_BeginRequest(object sender, EventArgs e) 
     { 
      if (writeBase) 
      { 
       writeBase = false; 
       //Save it to a location that you can easily reference from saved html pages.     
       string path = HttpContext.Current.Server.MapPath("~/App_Data/base.html"); 
       using (System.IO.TextWriter w = new System.IO.StreamWriter(path, false)) 
       { 
        w.Write(string.Format("<base href=\"{0}\"></base>", HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.PathAndQuery, ""))); 
        w.Close(); 
       } 
      }    
     } 

和添加文字控制你的aspx:

//the path here depends on where you are saving executed pages. 
System.Web.UI.LiteralControl l = new LiteralControl("<!--#include virtual=\"base.html\" -->"); 
Page.Header.Controls.AddAt(0,l); 

saved.html包含:

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<!--#include virtual="base.html" --> 
... 
</head> 
.... 
</html> 

UPDATE: 這是在asp.net開發服務器進行測試,如果託管的IIS下的應用爲approot將無法正確解析。要獲得正確的應用程序絕對url使用:

/// <summary> 
/// Get Applications Absolute Url with a trailing slash appended. 
/// </summary> 
public static string GetApplicationAbsoluteUrl(HttpRequest Request) 
{ 
return VirtualPathUtility.AppendTrailingSlash(string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Request.ApplicationPath)); 
}