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

前端之家收集整理的这篇文章主要介绍了asp.net – 在.css文件中引用应用程序相对虚拟路径前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我的应用程序的根目录下有一个“images”文件夹目录。如何从.css文件中,使用ASP.NET应用程序相对路径引用此目录中的图像。

例:

在开发中,〜/ Images / Test.gif的路径可能会解析为/MyApp/Images/Test.gif,而在生产中,它可能会解析为/Images/Test.gif(取决于应用程序的虚拟目录) 。我显然希望避免在环境之间修改.css文件

我知道您可以使用Page.ResolveClientUrl在渲染时动态地将url注入到控件的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:

    06001

原文链接:https://www.f2er.com/aspnet/253678.html

猜你在找的asp.Net相关文章