【问题标题】:ASP.NET redirect non existing pages to homepage in web.config using rewrite rulesASP.NET 使用重写规则将不存在的页面重定向到 web.config 中的主页
【发布时间】:2014-08-12 18:41:09
【问题描述】:

在我的 ASP.NET SPA 应用程序中,我使用 web.config 设置重写规则,因此我可以刷新页面而不会出错(使用 Angularjs 时),但我也想在不存在页面时重定向到应用程序的主页手动输入网址,请告知我应该如何修改下面的代码以适应这个:

<rewrite>
    <rules>
      <rule name="Products" stopProcessing="true">
        <match url="^products" />
        <action type="Rewrite" url="/" />
      </rule>
      <rule name="Orders" stopProcessing="true">
        <match url="^orders" />
        <action type="Rewrite" url="/" />
      </rule>
      <rule name="Home" stopProcessing="true">
        <match url="^home" />
        <action type="Rewrite" url="/" />
      </rule>
      <rule name="List" stopProcessing="true">
        <match url="^list" />
        <action type="Rewrite" url="/" />
      </rule>
    </rules>
  </rewrite>

【问题讨论】:

  • Angular 路由和 asp.net "routing" 不应相互冲突,在这种情况下,您的所有服务器路由都应该重定向到根目录,从那以后,Angular 应该负责路由您的 SPA .我认为您应该添加一个重定向到您的索引的 404 错误页面,与 url 重写本身无关。
  • 感谢您的回复,任何您可以参考的示例,对于这种情况。
  • 是的,我要把它添加为答案

标签: asp.net angularjs url-rewriting


【解决方案1】:

按照 Fedaykin 的建议(非常感谢),以下代码解决了这个问题:

<system.webServer>
    <httpErrors errorMode="Custom">
       <remove statusCode="404"/>
       <error statusCode="404" path="/Default.aspx" responseMode="ExecuteURL"/>
    </httpErrors>
</system.webServer>

由于我从事单页应用程序,在我的情况下路径等于“/”,如下所示:

<error statusCode="404" path="/" responseMode="ExecuteURL"/>

然后 Angularjs 路由会处理剩下的事情。

【讨论】:

  • @Fedaykin 我在我的 we.config 中按照你的方式进行了我的问题没有解决。你能帮我多一点吗
【解决方案2】:

您可以使用 404 错误处理重定向到您的主页(这里我假设它是 Default.aspx,但将其更改为您的主页),放在您的 webconfig 文件中:

<configuration>

   <system.web>
      <compilation targetFramework="4.0" />

      <customErrors mode="On" redirectMode="ResponseRewrite">
         <error statusCode="404" redirect="Default.aspx" />
      </customErrors>
   </system.web>

   <system.webServer>
      <httpErrors errorMode="Custom">
         <remove statusCode="404"/>
         <error statusCode="404" path="/Default.aspx" responseMode="ExecuteURL"/>
      </httpErrors>
   </system.webServer>

</configuration>

此外,在您的角度配置中,使用以下命令重定向到主页:

$routeProvider.
   when('/',{'templateUrl' : 'a.html'})
  .when('/b',{'templateUrl' : 'b.html'})
  .otherwise({redirectTo : '/'})
}

希望对您有所帮助。

【讨论】:

  • 它就像一个魅力。甚至您在 标签之间放置的部分似乎已经足够了,还是我仍然需要 的部分?非常感谢。我试图将您的回答标记为有帮助,但没有足够的声誉。
  • 嗨,尝试将其标记为答案,请参阅meta.stackexchange.com/questions/5234/…
  • 刚刚将其标记为答案。再次感谢。嘿,如果您对 Typeahead 有所了解,我还有另一篇需要帮助的帖子:stackoverflow.com/questions/25312303/…,如果您有心情,请随时查看。
  • @Fedaykin 我也有同样的问题,但我不知道为什么你的解决方案没有帮助我,你能帮我多一点吗。这是我的问题:stackoverflow.com/questions/26313790/…
猜你喜欢
  • 1970-01-01
  • 2015-01-20
  • 2013-04-17
  • 2018-05-28
  • 1970-01-01
  • 2019-09-01
  • 1970-01-01
  • 2019-08-02
  • 1970-01-01
相关资源
最近更新 更多