ASP.NET redirect non existing pages to homepage in web.config using rewrite rules

我与影子孤独终老i 提交于 2019-12-13 00:16:43

问题


In my ASP.NET SPA application I am using web.config to set Rewrite Rules, so I can refresh pages without error (while using Angularjs), but I also would like to redirect to application's homepage, when non-existing page manually entered into url, please advise how should I modify code below to accommodate this:

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

回答1:


You can use a 404 error handling to redirect to your homepage (here I´m assuming it´s Default.aspx, but change it to whatever is your home), on your webconfig file put:

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

Also, on your angular configuration use the following to redirect to home:

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

Hope that helps.




回答2:


As suggested by Fedaykin(thanks alot) the following code resolved this issue:

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

Since I work on Single Page Application, in my case path would equal to "/", like this:

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

and then Angularjs routing will take care of the rest.



来源:https://stackoverflow.com/questions/25271758/asp-net-redirect-non-existing-pages-to-homepage-in-web-config-using-rewrite-rule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!