3

有没有办法给 ASP.NET MVC 4 项目一个“公共”文件夹,它就像应用程序根目录一样,就像在 Ruby on Rails 中一样?

ASP.NET MVC 通常带有一个“内容”文件夹,您可以在其中放置静态提供的文件,如样式表、脚本和图像。但是这些文件的 URL 必须包含 Content 文件夹,例如<img src="/Content/logo.png">。是否可以将 Content 文件夹设置为应用程序的根目录,以便您可以使用它:<img src="/logo.png">

4

1 回答 1

1

我不知道为什么我以前没有想到这一点,但我能够通过 IIS URL 重写来完成这一点。以下规则假定您的静态文件所在的文件夹名为“Public”。当然,您可以随意命名文件夹。

<!-- Any direct references to files in the Public folder should be
     301 redirected to maintain canonical URLs. This is optional. -->
<rule name="Public folder canonical path" stopProcessing="true">
  <match url="^public/(.*)" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
  <action type="Redirect" url="{R:1}" appendQueryString="true" />
</rule>

<!-- Any URL that points to an existing file after prepending "Public" to it
     will serve that file. For example, if a file exists at /Public/style.css
     then the URL /style.css will serve that file. Likewise, if a file exists
     at /Public/images/logo.png, then the URL /images/logo.png will serve
     that file. Files in the Public folder will take precedence over files in
     the application root, so if a file /Public/script.js exists and a file
     /script.js exists, only the /Public/script.js file will be served. This
     also takes precedence over MVC routes. -->
<rule name="Public folder" stopProcessing="true">
  <match url=".+" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
    <add input="{URL}" pattern="^/Public/" negate="true" />
    <add input="{DOCUMENT_ROOT}/Public{URL}" matchType="IsFile" />
  </conditions>
  <action type="Rewrite" url="Public/{R:0}" appendQueryString="true" />
</rule>
于 2012-08-31T06:42:28.570 回答