Menu

Configure ASP.NET MVC application routes for Anguler SPA

If you ran in to a problem with Angular 2 html routing with you ASP.NET Core MVC application giving a 500 error when you do a browser refresh (F5), probably this tutorial if for you. We have to migrate one of the functionality from one project to another and we have a SPA as well as a few pages working with classic razor. rewriting the whole application was not an option within the given timeline.

Below is the route configuration.

app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "pureRazor",
        template: "PureRazor",
        defaults: new { controller = "PureRazor", action = "Index" }
    );

    routes.MapRoute(
        name: "error",
        template: "Home/Error",
        defaults: new { controller = "Home", action = "Error" }
    );

    routes.MapRoute(
        name: "Default",
        template: "{*.}",
        defaults: new { controller = "Home", action = "Index" }
    );
});

If you are using Angular 2 HTML5 routing still you might face few issues. SPA will still load but it will mess up the path to reference, reference will look related to your angular routs and get 404s. The solution is Anguler 2 HashLocationStrategy, which is putting a # in your url which will separate the Anguler 2 routs from MVC.

In you app.module.ts import LocationStrategy ,HashLocationStrategy and set the providers. see below

import { LocationStrategy, HashLocationStrategy } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppRoutingModule } from './app-routing.module';
import { HttpClient } from './../common/http.client';
import { AppComponent } from './app.component';

@NgModule({
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        AppRoutingModule,
        .....,
        .....,
    ],
    declarations: [    
        AppComponent,
        .....,
        .....,     
    ],
    providers: [
        .....,
        .....,
        HttpClient,
        { provide: LocationStrategy, useClass: HashLocationStrategy }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Enjoy

Leave a comment