【问题标题】:IIS URL Rewrite module: Url.Content() does not resolve CSS/Image path properlyIIS URL 重写模块:Url.Content() 无法正确解析 CSS/图像路径
【发布时间】:2013-08-29 08:25:01
【问题描述】:

我有一个带有布局页面等的标准 MVC3 项目。现在我需要制作漂亮的 URL。我开始玩 URL 重写模块。我正在尝试将http://localhost/Photographer/Pablo翻译成http://localhost/category-about.aspx?displayName=Pablo,这是我的重写规则(非常简单!):

  <system.webServer>
    <rewrite>
      <rules>
        <rule name="about" patternSyntax="Wildcard">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="\.png|\.js|\.css|\.jpg" negate="true" />
          </conditions>
          <match url="photographer/*" />
          <action type="Rewrite" url="category-about.aspx?displayName={R:1}" logRewrittenUrl="true" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

您在谷歌搜索尝试解决问题后添加的所有条件 - 但它们没有帮助。

我找到了这个页面:http://www.iis.net/learn/extensions/url-rewrite-module/url-rewriting-for-aspnet-web-forms - 它说 ~ 运算符在应用重写规则时被服务器正确处理。但这显然不会在我的情况下发生 - 请参阅所附图片:

我的问题的解决方案是什么?我应该如何引用 CSS/JS 文件?我在 IIS 7.5 上使用 MVC3。

更新: 图片不是很清楚 - 但它表明我的 MasterLayout 页面有

<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />

但它被解析为

http://localhost/Photographer/Content/Site.css - and it gives 404

而不是

http://localhost/Content/Site.css - which gives 200

当我请求此 URL 时:http://localhost/Photographer/Pablo。逻辑工作正常 - 我的控制器获取请求并呈现页面 - 但它的 CSS 和图像丢失(因为它们前面有错误的根文件夹)。

【问题讨论】:

  • IIS 7.5 如果有帮助的话...

标签: asp.net asp.net-mvc iis relative-path url-rewrite-module


【解决方案1】:

尝试使用 Request.ApplicationPath。这样的事情应该可以工作:

<link href="@(Request.ApplicationPath + "Content/Site.css")" rel="stylesheet" type="text/css" />

【讨论】:

  • 当重写规则到位时,Url.Content 中似乎存在错误。我遇到了一些描述这个确切问题的其他帖子,但没有关于根本原因的详细信息。我实际上已经更新了我的回复,因为如果您依赖 Request.ApplicationPath 将应用程序根添加到您的路径中,则无需实际使用 Url.Content。
  • 请注意,Request.ApplicationPath 不包含尾部斜杠。我试图编辑答案以更新它,但它说我的更新必须是 6 个字符。我不想找到其他 5 个字符来更改。
【解决方案2】:

你说了那句话:

<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" />

被解析为

“http://localhost/Photographer/Content/Site.css”

,这是绝对正确的,这就是它的解决方法。你的css在哪里,css中图片的路径是否正确?

【讨论】:

  • 为什么你认为它是正确的?应该是localhost/Content/Site.css
  • 因为“~”将您带到根虚拟目录,现在的问题是您如何在 IIS 中映射它。在启动应用程序时,您获得的 URL 是什么?
  • 查看此链接:stackoverflow.com/questions/10482299/… 希望对您有所帮助。到那时我会尝试复制您面临的问题。
【解决方案3】:

而不是这个

<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />

试试这个不带波浪号 (~)

<link href="@Url.Content("/Content/Site.css")" rel="stylesheet" type="text/css" />

这应该解决您想要的http://localhost/Content/Site.css

【讨论】:

    猜你喜欢
    • 2020-09-07
    • 2010-10-24
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 2015-05-11
    • 2023-01-24
    • 1970-01-01
    相关资源
    最近更新 更多