2009-06-03 15 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)); 
}