【问题标题】:How to deal with web.config in a url search term如何处理 url 搜索词中的 web.config
【发布时间】:2012-07-02 14:51:45
【问题描述】:

我正在 ASP.NET MVC3 中创建一个搜索页面。

调用动作的url是:

http://mydomain/Search?q=searchterm

如果我搜索关键字“web.config”,它就可以正常工作:

http://mydomain/Search?q=web.config

但现在,我希望网址是:

http://mydomain/Search/searchterm

我已经通过将路由添加到 global.asax 来完成此操作,但是当我搜索“web.config”时,例如http://mydomain/Search/web.config,服务器将结束我的请求,因为它认为我正在请求物理 web.config 文件搜索目录。

有没有办法让asp.net将url“search/{q}”中的{q}视为搜索动作的参数,而不是文件的请求?

【问题讨论】:

标签: asp.net asp.net-mvc url-rewriting url-routing


【解决方案1】:

Global.asax 中的 RegisterRoutes 中,您可以启用对现有文件的请求以通过路由引擎:

routes.RouteExistingFiles = true;

请注意,如果您这样做,所有请求现在都将通过 ASP.NET MVC 路由引擎。因此,如果您不想看到损坏的图像或 javascript 和 CSS 引用,则需要明确排除它们:

routes.IgnoreRoute("scripts/{resource}.js");
routes.IgnoreRoute("content/{resource}.css");
routes.IgnoreRoute("iamges/{resource}.png");
routes.IgnoreRoute("iamges/{resource}.jpeg");
...

此外,如果您在 IIS 7+ 中托管您的应用程序,您需要删除一些通常会阻止您提供 web.config.config 文件的安全过滤器:

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true" />
    <security>
      <requestFiltering>
        <fileExtensions>
          <remove fileExtension=".config"/>
        </fileExtensions>
        <hiddenSegments>
          <remove segment="web.config"/>
        </hiddenSegments>
      </requestFiltering>
    </security>
</system.webServer>

【讨论】:

  • 这似乎是个好主意,但是在我在 global.asax 中添加此规则后,我的所有图像都没有显示:(
  • 确保您已从路由中排除静态资源:routes.IgnoreRoute("images/{image}.png");。对您需要处理和调整网站网址的其他静态资源执行相同操作。
  • 哇,在我将您的代码添加到 system.webServer/security 后它就可以工作了。谢谢。
【解决方案2】:

您可以使用 IIS 中的 URL 重写器模块为您执行此操作;它将从Global.asax 中删除必要的逻辑,并允许您在整个网站上使用它来简化网址。

Rewriter Module

Adding a Rewriter Rule

示例规则:

<rewrite>
  <rules>
    <rule name="Rewrite to search">
      <match url="^search/([_0-9a-z-]+)" />
      <action type="Rewrite" url="search.aspx?q={R:1}" />
    </rule>
  </rules>
</rewrite>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    相关资源
    最近更新 更多