Building ASP.NET Core MVC as SPA using Angular 2 and TypeScript

ASP.NET Core as MVC application is completely modular, seamlessly integrate with various JavaScript based frameworks like Angular 2, Angular 1.*, React, Knockout, JQuery etc.

In this article we will learn how to build ASP.NET Core MVC as a Single Page Application (SPA) using latest Angular 2.

When working with Angular 2 and ASP.NET Core, we should consider these points

  • Angular 2 build strategy to be used i.e. Gulp, Webpack, Rollup. The usage of Webpack is optimal approach for build mechanism.
  • Using ASP.NET Core tag helpers features also.
  • Simpler approach to include 3 party libraries
  • Working in development or production mode with ease.

These steps can be followed on Windows OS, Linux or Mac OS machines

Microsoft ASP.NET team have built up excellent infrastructure known as JavaScriptServices for building SPA based applications. At present they provide Angular 2/ React/ Knockout infrastructure. Lets get started then

Step 1 – Software prerequisites

The following software needs to be installed

  • Visual Studio Code – Light weight cross platform editor
  • Install ASP.NET and .NET Core SDK appropriate for OS
  • Latest NodeJS and NPM.
  • Install Visual Studio 2015 Update 3 (optional step). For die hard fan of VS IDE, we can use it too.

We will be using Yeoman generators for scaffolding applications. The project template for ASP.NET Core SPA needs to be installed too generator-aspnetcore-spa. Run below command to install them

Step 2 – Creating ASP.NET Core SPA app with Angular 2

Now lets create the SPA application using yeoman generator. Give a name to application and select “Angular 2” application in options. It’s command line way of creating applications

After creating ASP.NET Core MVC application, all the NPM packages are installed automatically. It takes few minutes to install all NPM packages.

Run dotnet restore from CLI to ensure all ASP.NET NuGet packages are installed

Step 3 – Understanding the project structure

The generator has created ASP.NET Core MVC application in form SPA with Angular 2, this means we already have MVC application baked with Angular 2 application. Isn’t it wonderful, lets understand project structure that is created. core

Project Structure of MVC SPA with Angular 2

  1. ClientApp is an Angular 2 applications with modules, components, templates, Routing etc. Any further Angular 2 development code should be written here.
  2. Controllers is folder containing ASP.NET Core controllers. Both MVC and Web API controller can be written here.
  3. node_modules contains all the NPM packages installed. Package.json contains list of NPM packages needed to work with Angular 2, other technologies like bootstrap, JQuery etc. As soon as project gets created from yeoman, scripts are run from project.json
  4. Views folder contains the MVC Razor HTML files like Layout, Error etc. This shows that we are using ASP.NET Core MVC application.
  5. dist compiled folder containing Angular 2 main application, vendor files. It’s placed in wwwroot folder as its web root folder.
  6. package.json and project.json are the essential files for Angular 2 and ASP.NET Core apps. They contain all the dependencies, tooling, build information.
  7. webpack configuration files does the module bundling tasks. For Angular 2 to load, prepare bundles based on vendor files, app related files, minify when in prod are all performed using webpack configuration.

Step 4 – Two ways of running the app

This application can be run either in CLI mode or using Visual Studio Code launch settings.

Run using CLI mode

We need to run the command dotnet run from the CLI to start the application. It starts application, listens on localhost 5000 port. Open browser, navigate http://localhost:5000 to see the application in action.

When running using CLI, the application run in PROD and even Angular 2 app runs in PROD mode. However you can change it to run under Development mode too.

Run using VS Code

When you open application in VS Code, you will see following warning that required assets needs to created. Click Yes. core

Click Yes will create .vscode folder containing two JSON files launch.json and tasks.json. They have predefined code for running application.

Opening launch.json, read through .NET Core Launch (web) configuration. It contains necessary config entries so that it can run on any OS. Also env variable ASPNETCORE_ENVIRONMENT is Development.

Just pressing the F5 the application starts running, open browser automatically, reloads on file changes and most important run in DEVELOPMENT mode.

This is how the application looks like when run using either CLI or VS Code. It’s different from the usual ASP.NET web application because this more focused for being SPA. core

Application running in browser

What’s so special about using JavaScript services?

Personally I liked the way Angular 2 and ASP.NET Core are used together here, because

  • Developed from Microsoft ASP.NET team. Its constantly updated with framework changes.
  • Uses webpack for module bundling, soon webpack 2 will make this light weight.
  • Very simple way to tweak to run for DEV or PROD mode.
  • It also uses Angular Universal for server side rendering of Angular 2 application. This helps load apps much faster.
  • Super simple integration with third party JS libraries using Vendor packaging.
  • Inbuilt Docker support, makes deployment easy on docker containers.
  • Hot Module replacement supported when application run in development.
  • We can write Web API in the same project to access data, in turn displayed on Angular 2 apps

So far I have integrated Angular 2 in ASP.NET (MVC 5 and Core) in different ways but this is most elegant way.

Hello Readers, let me know in comments if detailed code walk through needed.

You may also like...

22 Responses

  1. brylle says:

    Hi,I am currently using this template after using it for almost 3 months my application suddenly stops running. when i try to debug it the error comes when executing this code

    app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
    HotModuleReplacement = true

    any advise you may know that is causing the problem?


  2. Mark says:

    I really like your articles and examples; they are exactly what I have been looking for, but you have not posted anything in over 6 months. I hope you plan to continue posting examples and keep this site current. Thanks!

  3. Stuart Bloom says:

    I know its been a while since this article has been written, but I just wanted to say thank you; It has been a great help for someone moving from Knockout to Angular 🙂

    One question, following this style of application, is it possible to access the application object from within developer tools?

    Thanks in advance, and thanks again for a great article.


  4. hamed says:

    very useful article.
    I just start using angular, i want to ask regarding IIS deployment.

    Which files i should use it to host it on IIS?


  5. Sebastiao Herodes says:

    And how about Visual Studio 2015 Update 3 (optional step). Can you explain how run this application inside Visual Studio 2015?

  6. You’re instructions in Step 2 are too sparse and not very specific.

  7. Robert says:

    Didn’t work for me. After installing, I created the new project:

    c:\Projects> yo aspnetcore-spa

    And when I ran it I got this error. Any idea what went wrong?

    ( Oops.
    500 Internal Server Error
    The system cannot find the file specified
    at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
    at System.Diagnostics.Process.Start()
    at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
    at Microsoft.AspNetCore.NodeServices.HostingModels.OutOfProcessNodeInstance.LaunchNodeProcess(ProcessStartInfo startInfo)
    at Microsoft.AspNetCore.NodeServices.HostingModels.OutOfProcessNodeInstance..ctor(string entryPointScript, string projectPath, String[] watchFileExtensions, string commandLineArguments, ILogger nodeOutputLogger, IDictionary environmentVars, int invocationTimeoutMilliseconds, bool launchWithDebugging, int debuggingPort)
    at Microsoft.AspNetCore.NodeServices.HostingModels.HttpNodeInstance..ctor(string projectPath, String[] watchFileExtensions, ILogger nodeInstanceOutputLogger, IDictionary environmentVars, int invocationTimeoutMilliseconds, bool launchWithDebugging, int debuggingPort, int port)
    at Microsoft.AspNetCore.NodeServices.NodeServicesFactory.CreateNodeInstance(NodeServicesOptions options)
    at Microsoft.AspNetCore.NodeServices.c__DisplayClass0_0.b__0()
    at Microsoft.AspNetCore.NodeServices.NodeServicesImpl.CreateNewNodeInstance()
    at Microsoft.AspNetCore.NodeServices.NodeServicesImpl.GetOrCreateCurrentNodeInstance()
    at Microsoft.AspNetCore.NodeServices.d__10.MoveNext()
    One or more errors occurred. (The system cannot find the file specified)
    Line 42: {
    Line 43: app.UseDeveloperExceptionPage();
    Line 44: app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
    Line 45: HotModuleReplacement = true
    Line 46: });

  8. Henk says:

    Hi. Very nice article..

    I would be very interested in a more detailed code walk through with a Web API integrated in the app.

  9. Vladimir says:

    Hi. Nice article!
    Want to know, what is the difference between implementing ASP.NET MVC with Angular 2 and pure ASP.NET WebApi with Angular 2 ?

    • Thanks !!
      A pure ASP.NET web api is application without UI, to build UI we can either create separate app in MVC or pure Angular 2 application.

      ASP.NET MVC itself is UI framework, but to have more client side capabilities Angular 2 can be used.

      Hope this helps you.

  1. November 7, 2016

    […] on November 6, 2016 submitted by /u/mithunvp [link] [comments] Leave a […]

Leave a Reply