简体   繁体   中英

IIS URL Rewrite module: Url.Content() does not resolve CSS/Image path properly

I have a standard MVC3 project with layout page etc. Now I need to make pretty URLs. I started playing with URL rewrite module. I'm trying to translate http://localhost/Photographer/Pablo into http://localhost/category-about.aspx?displayName=Pablo , and here is my rewrite rule (very simple!):

  <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>

all conditions you see I added after googling trying to solve the issue - they did not help though.

I found this page: http://www.iis.net/learn/extensions/url-rewrite-module/url-rewriting-for-aspnet-web-forms - which says that ~ operator is properly treated by the server when rewriting rules are applied. But that's clearly does not happen in my case - please see the image attached:

图像附加

What is the solution to my problem? How should I reference CSS/JS files? I'm using MVC3 on IIS 7.5.

UPDATE: image is not very clear - but it shows that my MasterLayout page has

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

but it's resolved as

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

instead of

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

when I request this URL: http://localhost/Photographer/Pablo . Logic works fine - my controller gets the request and renders the page - but it's CSS and images are missing (because they have wrong root folder prepended).

Try using Request.ApplicationPath. Something like this should work:

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

You said the line:

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

is resolved as

"http:// localhost/Photographer/Content/Site.css"

, which is absolutely correct this is how it would be resolved. Where does your css lie, is the path for the image in css correct?

Rather than this

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

Try this without the tilde (~)

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

This should resolve to your desired http://localhost/Content/Site.css

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM