Search code examples
asp.netangularjsasp.net-web-apiasp.net-web-api-routing

Modify and redirect for not found URl in web api


I enabled Html5 mode in angular for my project witch convert my URl from

A: qwe.com/#/products

to

B: qwe.com/products

But the problem is in this case if user trying to directly go to B, server (web api) catch the Url and return not found error so I need a way to catch all not found in server add a # sign to that and redirect to new Url but how should I do it?

Update:

Thanks to @Travis Collins

In Global.asax

private const string ROOT_DOCUMENT = "/index.html";

protected void Application_BeginRequest( Object sender, EventArgs e )
{
   string url = Request.Url.LocalPath;
   if ( !System.IO.File.Exists( Context.Server.MapPath( url ) ) )
       Context.RewritePath( ROOT_DOCUMENT );
}

Solution

  • You need to do the rewrite on your server end for this. This will make the web server still serve your index.html file even when a request comes in for /products or anything else. In IIS for example, you would do this in web.config:

    <system.webServer>
      <rewrite>
        <rules> 
          <rule name="Main Rule" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />                                 
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            </conditions>
            <action type="Rewrite" url="/" />
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
    

    Lots of other servers are explained here: https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-configure-your-server-to-work-with-html5mode