加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 18:42:06 所属栏目:asp.Net 来源:网络整理
导读:假设我的应用程序的根目录下有一个“images”文件夹目录。如何从.css文件中,使用ASP.NET应用程序相对路径引用此目录中的图像。 例: 在开发中,?/ Images / Test.gif的路径可能会解析为/MyApp/Images/Test.gif,而在生产中,它可能会解析为/Images/Test.gif
假设我的应用程序的根目录下有一个“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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读