asp.net - 在 .css 文件中引用应用程序相对虚拟路径

标签 asp.net css background-image dynamic-css

假设我的应用程序根目录下有一个“图像”文件夹目录。我如何从 .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?

  1. 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>
  1. 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; }

  2. .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/

相关文章:

c# - 为什么 HTML Agility Pack HtmlDocument.DocumentNode 为空?

css - 为缩放圆圈动画添加边框

css - 带文本背景的标题

android - 绘制可滚动的平铺背景

c# - REST Api 服务器挂起大量请求(使用 c# HttpClient)

c# - 如何在类中设置应用程序状态值?

c# - ASP.Net:如何打开第二个窗口并在主窗口中写一些东西?

css - Chrome 而非 IE 中的 Div 之间的垂直空间

css - 如何为 Rails 3 站点中的每个页面设置不同的背景图片?

html - 尝试向下拉伸(stretch)背景,但仍留有空白