假设我的应用程序根目录下有一个“图像”文件夹目录。我如何从 .css 文件中使用 ASP.NET 应用程序相对路径引用此目录中的图像。
例子:
在开发中,~/Images/Test.gif 的路径可能会解析为 /MyApp/Images/Test.gif,而在生产中,它可能会解析/Images/Test.gif(取决于应用程序的虚拟目录)。显然,我想避免在环境之间修改 .css 文件。
我知道您可以使用 Page.ResolveClientUrl 在呈现时动态地将 url 注入(inject)到控件的 Style 集合中。我想避免这样做。
最佳答案
不幸的是,Firefox 在这里有一个愚蠢的错误...路径是相对于页面的路径,而不是相对于 CSS 文件的位置。这意味着如果您在树中的不同位置有页面(例如在根目录中有 Default.aspx 而在 View 文件夹中有 Information.aspx),则无法使用工作相对路径。 (IE会正确解析相对于CSS文件位置的路径。)
我唯一能找到的是关于 http://www.west-wind.com/weblog/posts/269.aspx 的评论但是,老实说,我还没有成功。如果我这样做,我将编辑此评论:
re: Making sense of ASP.Net Paths by Russ Brooks February 25, 2006 @ 8:43 am
No one fully answered Brant's question about the image paths inside the CSS file itself. I've got the answer. The question was, "How do we use application-relative image paths INSIDE the CSS file?" I have long been frustrated by this very problem too, so I just spent the last 3 hours working out a solution.
The solution is to run your CSS files through the ASPX page handler, then use a small bit of server-side code in each of the paths to output the root application path. Ready?
- Add to web.config:
<compilation debug="true">
<!-- Run CSS files through the ASPX handler so we can write code in them. -->
<buildProviders>
<add extension=".css" type="System.Web.Compilation.PageBuildProvider" />
</buildProviders>
</compilation>
<httpHandlers>
<add path="*.css" verb="GET" type="System.Web.UI.PageHandlerFactory" validate="true" />
</httpHandlers>
Inside your CSS, use the Request.ApplicationPath property wherever a path exists, like this:
#content { background: url(<%= Request.ApplicationPath %>/images/bg_content.gif) repeat-y; }
.NET serves up ASPX pages with a MIME type of "text/html" by default, consequently, your new server-side CSS pages are served up with this MIME type which causes non-IE browsers to not read the CSS file correctly. We need to override this to be "text/css". Simply add this line as the first line of your CSS file:
<%@ ContentType="text/css" %>
关于asp.net - 在 .css 文件中引用应用程序相对虚拟路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/89418/