ASP.Net URL Rewrite with Web API and AngularJS

Looking at many AngularJS samples you will see they are served using the following format.

https://somewhere.com/index.html#/routePart1/routePart2/someId

Having the index.html# always be part of the route is not very pleasing visually, but there is a way to end this and change the application URLs to lose reference to the index page.

Allowing clean URLs for an AngularJS app served by an IIS or IIS Express server is a several step process.

Note: for IIS, you must install the the Microsoft URL Rewrite Module 2.0 for IIS (x64) for IIS so that the rewrite rules specified in the web.config are recognized. Without this extension, IIS will throw the following error:

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Following these steps will allow for clean URLs in the application such as:

https://localhost/orders

replacing the default URL format of:

https://localhost/index.html#/orders

ASP.Net Application Modification Points

  • Works with IIS and IIS Express.
  • Add rewrite rules to web.config file

    <rewrite>
      <rules>
        <clear />
        <!-- Clean URL Rules -->
        <!-- Exclusions from redirect: notice api/* and token at end of list. -->
        <rule name="URL Exclusions" stopProcessing="true">
          <match url="(app/.*|scripts/.*|content/.*|fonts/.*|images/.*|api/*|token)" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
          <action type="None" />
        </rule>
        <!-- Redirect for application: change "app/index.html" to point the apps start page. -->
        <rule name="URL Redirect">
          <match url="(.*)" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
          <action type="Rewrite" url="app/index.html" />
        </rule>
      </rules>
    </rewrite>
    
  • Modify “URL Exclusions rule to include project content directories

    • Each item should be separated by a pipe character
    • Add the “api” and “token” routes to the list in addition to the content as these should not be redirected
    • If the api has additional top level routes other than “api” and “token”, add these to the exclusions
  • Ensure that routes in the application fit with the exclusions.

    • Check WebApiConfig.cs and contoller attribute routes.

AngularJS Application Modification Points

  • In route config function.

    • Ensure $routeProvider.when routes begin with “/”.
    • Add following code javascript **$locationProvider.html5mode(true);**
  • In application layout page, add to base element the head

    <head>
    ...
    <base href="/" />
    </head>
    
  • Remove the # character from html navigation links (like those found in the nav bar) and from any references in the Javascript of the application (like those using $location.path(‘/path’)).