Angular2 "Tour of Heroes" with ASP.NET MVC Core

November 06, 2016

Sometimes it is not easy to decide what pattern to choose between single-page application (SPA) or traditional HTML pages. What if you need SPA only for the particular part of your website?

In general, mixing these two is not recommended. But if you have an existing traditional web app with tons of pages – conversion will not be easy and should be done in multiple steps.

So, I had the challenge migrating big ASP.NET MVC project to Angular2. As result I decided to share my experience and create a sample of Angular2 “Tour of Heroes” running as ASP.NET MVC Core:

github.com/yfranz/angular2-heroes-with-mvc-core-net

My goal was to make as few changes as possible and preserve the original structure of the tutorial. Without diving into much detail, here are the most important highlights:

All tutorial scripts ended up in "AppScripts" folder.

HTML pages have been converted into .cshtml. Otherwise using MVC would not have much sense. Typescript compiler generates javascript into "wwwroot/ts-scripts" folder. See tsconfig.json for all typescript settings.

As few changes as possible: special handling for CSS and HTML files

MVC is not designed to keep static files (e.g. css) with views together. Ideally you have to use wwwroot for all your static files. However, with my goal of making as few changes as possible, I added special handling of css and cshtml files in HomeController. It is not recommended in real projects thought.

There two methods GetCss and GetObject. Method GetCss simply returns file content for any *.css file requested in ts-scripts from AppScripts:


[HttpGet("/ts-scripts/{name}.css")]
public IActionResult GetCss(String name)
{
    byte[] fileBytes = System.IO.File.ReadAllBytes("AppScripts/" + name + ".css");
    return File(fileBytes, "text/css");
}

Method GetObject renders view in the similar fashion:


[HttpGet("/ts-scripts/{name}.cshtml")]
public IActionResult GetObject(String name)
{
    return View("~/AppScripts/" + name + ".cshtml");
}

HeroesController was introduced instead of in memory web api

HeroesController receives “injected” IHeroRepository for all the operation with the model