ASP.NET redirect non existing pages to homepage in

2019-08-01 12:18发布

问题:

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.