Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 routing in Angular2 App with ASP.Net Core MVC and ASP.Net Web Api

I am develop Angular2 App with ASP.Net Core MVC and ASP.Net Web Api.

Here is my basic architecture.

ASP.Net Core MVC Project (MyProject.Web)

  • Nuget, npm, and bower is used for dependencies. Bower is used to copy the npm dependencies from node_modules to wwwroot/libs/
  • Home/Index controller's action delivers the first page which loads Angular2 and other dependencies.
  • Templates are loaded from ActionMethods i.e. Home/About
  • SystemJS loads the modules.
  • Angular2's http service calls the ASP.Net Web Api Project (a separate project than mvc)

ASP.Net Web Api Project (MyProject.Api) - Each Controllers is designated for CRUD operations of an entity, and responses to Angular2's http

Problem: I am not able to use HTML5 routing and am forced to hash routing because html5 routing calls the server and my MVC project does not have the corresponding controller. So server doesn't return anything.

like image 536
Super Coder Avatar asked Feb 06 '23 08:02

Super Coder


1 Answers

If you plan to use on IIS, you can use URL rewriting module. It basically tells web server to rewrite all routing URLs to index.html. .

<?xml version="1.0" encoding="utf-8"?>
<system.webServer>
   <handlers>
      <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule"
resourceType="Unspecified"/>
   </handlers>
   <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%"
stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout"
forwardWindowsAuthToken="false" />
      <rewrite>
         <rules>
            <rule name="Angular 2 pushState routing" stopProcessing="true">
               <match url=".*" />
               <conditions logicalGrouping="MatchAll">
                  <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
                  <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
                  <add input="{REQUEST_FILENAME}" pattern=".*\.[\d\w]+$" negate="true" />
                  <add input="{REQUEST_URI}" pattern="^/(api)" negate="true" />
               </conditions>
               <action type="Rewrite" url="/index.html" />
            </rule>
         </rules>
      </rewrite>
   </system.webServer>
</configuration>
like image 64
Win Avatar answered Feb 08 '23 15:02

Win