Creating a simple API with ASP.NET Core

I posted about ASP.NET Core in the past. In this opportunity, I would like to share a simpler introduction to it using the nodejs’ approach. This approach consists in showing how to create a simple Web API (first with the http module and then using the express framework).

ASP.NET Core

ASP.NET Core is the new web framework in the .NET world, which is open-source (at GitHub) and cross-platform. It was created with focus on modern web development which are generally deployed in clouds environments and serves as backends for mobile apps or IoT apps as well as web apps. Additionally, as part of the redesign of ASP.NET, ASP.NET Core apps can run on .NET Core or on the full .NET Framework and ships entirely as NuGet packages (in a similar way as, for example, node.js apps).

In order to start working with ASP.NET Core, you should install .NET Core first. To do this, visit the oficial site and follow the instructions based on your preferred platform. Furthermore, you will need an editor for which I suggest Visual Studio Code (which is also cross-platform) along with the C# extension.

Creating the base app

Now that you have your environment ready, the first thing that you usually do in node.js is to create the package.json file. To do this, you would run the npm start command to create that file. In a similar way, for a new .NET Core app you will execute dotnet new. By executing this command, you will get the base structure for the app, which consist in two files: project.json and Program.cs. The first one contains the program metadata, including frameworks versions as well as dependencies. The other one is the program code itself.

Similar to node’s npm install, you should now restore the dependencies by executing dotnet restore. This will generate a new file, project.lock.json, which contains all the required information for running the app. At this point, you can see your first “Hello World!” output by running the dotnet run command. Note that this command checks the project source every time to determine if a re-build is necessary. Because of this, this command is intended for active development scenarios. In other scenarios you can execute dotnet build and then run the generated .dll file.

Adding the ASP.NET Core magic

After having the running .NET Core app, you will need to add the Microsoft.AspNetCore.Server.Kestrel dependency in order to run a simple web server similar to what the nodejs’s http module can do. In order to do this, open the project.json file and update the dependencies section as shown below.

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

Again, you will need to execute dotnet restore to restore the new dependency and update the project.lock.json file accordingly. After doing that, open the Project.cs file to add the following using statements at the top.

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;

Update the content of the Main function with the following. This will create the web host, configure it to use Kestrel and return to every request the “Hello World!” message.

public static void Main(string[] args)
{
   var host = new WebHostBuilder()
       .UseKestrel()
       .Configure(app => app.Run(context => context.Response.WriteAsync("Hello World!")))
       .Build();

   host.Run();
}

Same as you did before, execute the updated code with dotnet run. Then, open a browser and navigate to localhost:5000. As result, you should be able to see the new “Hello World!” message in your browser.

Adding the MVC framework

At this point in any node.js introduction you would include express, which facilites you creating routes as well as getting the request information. For ASP.NET Core we will include Microsoft.AspNetCore.Mvc as dependency.

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0"
  },
  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

Now, create new file named Startup.cs and add the following content, replacing the aspnetcoreapp namespace with the one use have in the Program.cs file. This configure the MVC services that take advantage of the build-in dependency injection feature. Additionally, configure the application itself to use the MVC framework, adding support for Controllers.

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace aspnetcoreapp
{
  public class Startup
  {
    public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc();
    }

    public void Configure(IApplicationBuilder app)
    {
      app.UseMvc();
    }
  }
}

After creating this file, you will need to update the Program.cs again, using the following code which configures the Startup class that you just created instead of a custom configuration.

public static void Main(string[] args)
{
  var host = new WebHostBuilder()
    .UseKestrel()
    .UseStartup<Startup>()
    .Build();

  host.Run();
}

Creating the first Controller

Create a new folder named Controllers and then create a new file named ValuesController.cs in it. Add the following content to the new file to have a simple API that returns a list of values as json.

using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;

namespace aspnetcoreapp.Controllers
{
  [Route("api/[controller]")]
  public class ValuesController : Controller
  {
    [HttpGet]
    public IEnumerable<string> Get()
    {
      return new string[] { "value1", "value2" };
    }
  }
}

Once this is ready, you just need to execute dotnet run again and navigate to localhost:5000 in your browser to see the list values.

Manifoldjs, a tool to create hosted apps

Modern web technologies are evolving not only to create faster and complex websites but also to create apps. There are plenty of examples for this. First of all, node.js, which is the one of the best examples, moving JavaScript to the server side. Then, you have electron, which is the technology behind Visual Studio Code, atom, the slack client and kitematic. Furthermore, you can think of frameworks that enables to create mobile apps using web technologies like apache cordova, ionic and React Native. However, you can go a step further creating a website and apps all in one using Manifoldjs.

Manifoldjs creates hosted web apps and some polyfill apps for Android, iOS, Windows 8.1, Windows Phone 8.1, Windows 10, FirefoxOS, Chrome, and the web, all based on the W3C Manifest for Web Apps. In addition to these platforms, the new version of manifoldjs supports creating your own platforms.

manifoldjs

So, what is a “Hosted Web App”? It’s a store app (i.e. apps that can be downloaded from Google Play or Windows Store), whose content is hosted on a web server. In other words, it’s a website converted into an installable app. You can find more information about hosted web apps in this post.

A W3C Manifest for web apps is a standardized JSON-based manifest that provides developers a centralized place to put metadata associated with a web application. With this manifest, you can forget about using all the platform-specific meta tags that set the different size icons for each platform and other settings. In order to support this manifest on your site, you just need to add a single <link> tag:

<link rel="manifest" href="manifest.json">

An example of a manifest.json could be something like:

{
    "name": "manifold.js",
    "short_name": "mjs",
    "icons": [{
        "src": "images/tiny.png",
        "sizes": "70x70",
        "type": "image/png"
    }],
    "start_url": "/",
    "scope":"http://www.manifoldjs.com/*"
    "display": "standalone",
    "orientation": "landscape"
}

If you want to generate a manifest.json for your site, there are several sites that can help you, for example, you can use the manifoldjs generator site or this one.

Of course, like most cool new features on the block, not every browser supports it yet. However, you can use the ManUp.js polyfill, for example, which will create the required meta tags on your site based on the manifest.json file. You can find more information about W3C Manifest and ManUp.js in this post.

Manifoldjs provides three ways to create your apps:

  • A node-based command-line interface (CLI) which you can install with npm and is easy to use.
  • A node.js module interface, which you can use to create your own tool just by adding the module as a common npm dependency in your node.js app.
  • A website that generates the apps for you: http://www.manifoldjs.com/generator

I will try to explain each scenario in more detail in future posts, but for now, the website is the easiest option.

To sum up, with your site, a W3C Manifest JSON file and manifoldjs, you can easily leverage your site in a cool way, creating Store apps for today’s most important platforms.

ASP.NET Core and Angular 2

ASP.NET Core and Angular 2 with TypeScript Writing web applications nowadays is becoming a bit more complex as the frameworks evolve taking advantage of other frameworks/tools. That’s the case of Angular 2 (which was developed using TypeScript) and ASP.NET Core with take advantage of npm and bower for the dependencies as well as gulp for performing some tasks. In this article, I will show you how to configure ASP.NET Core and Angular 2 using TypeScript to create your rich client-side apps.

ASP.NET Core is a new open-source and cross-platform framework for building modern cloud-based Web applications using .NET. It was built from the ground up to provide an optimized development framework for apps that are either deployed to the cloud or run on-premises. It consists of modular components with minimal overhead, so you retain flexibility while constructing your solutions. It has evolve taking concepts from node.js and other platforms.

Angular is a development platform for building mobile and desktop web applications using modern web standards. Is an open-source JavaScript framework that augments browser-based applications with Model-View-Controller (MVC) capability, facilitating both development and testing. If you know the previous version, Angular 2 might seems to be a completely different framework, but the main concepts are there. One of the main differentiators is that Angular 2 is written in TypeScript, a superset of JavaScript that compiles to clean JavaScript output. Because its transcompiled to JavaScript, you can use the framework from JavaScript as well as from TypeScript itself.

Now, let’s start configuring a project with both technologies, ASP.NET Core and Angular 2. I’ll assume that you have an ASP.NET Core project created, with MVC configured, although this is not a requirement for using both technologies together. If you need to create a new project, just use the Web Application template in Visual Studio or using the aspnet’s Yeoman generator.

In order to have ASP.NET Core and Angular 2 running together, you’ll need to have the Angular 2 dependencies in place. Angular 2 is distributed using the npm package manager. Open the npm’s package.json file located at the root of your project and add the following dependencies to it.

  "dependencies": {
    "angular2": "2.0.0-beta.9",
    "systemjs": "0.19.24",
    "es6-shim": "^0.33.3",
    "rxjs": "5.0.0-beta.2"
  },

If you are using Visual Studio, after saving the file, it will download the new dependencies (else, just run npm install in the same folder). The files will be downloaded in the node_modules folder, which is not served as default by ASP.NET. You could configure ASP.NET to serve this folder, but it’s better to just copy the files to the wwwroot folder using a gulp tasks. Add the following code in the gulpfile.js. This will add a few tasks to copy each of the dependencies to the wwwroot/lib/npmlibs folder, as well as a task named copy-deps that will run all the others.

paths.npmSrc = "./node_modules/";
paths.npmLibs = paths.webroot + "lib/npmlibs/";

gulp.task("copy-deps:systemjs", function () {
    return gulp.src(paths.npmSrc + '/systemjs/dist/**/*.*', { base: paths.npmSrc + '/systemjs/dist/' })
         .pipe(gulp.dest(paths.npmLibs + '/systemjs/'));
});

gulp.task("copy-deps:angular2", function () {
    return gulp.src(paths.npmSrc + '/angular2/bundles/**/*.js', { base: paths.npmSrc + '/angular2/bundles/' })
         .pipe(gulp.dest(paths.npmLibs + '/angular2/'));
});

gulp.task("copy-deps:es6-shim", function () {
    return gulp.src(paths.npmSrc + '/es6-shim/es6-sh*', { base: paths.npmSrc + '/es6-shim/' })
         .pipe(gulp.dest(paths.npmLibs + '/es6-shim/'));
});

gulp.task("copy-deps:rxjs", function () {
    return gulp.src(paths.npmSrc + '/rxjs/bundles/*.*', { base: paths.npmSrc + '/rxjs/bundles/' })
         .pipe(gulp.dest(paths.npmLibs + '/rxjs/'));
});

gulp.task("copy-deps", ["copy-deps:rxjs", 'copy-deps:angular2', 'copy-deps:systemjs', 'copy-deps:es6-shim']);

Now that you have the Angular 2 dependencies ready to be served in your project, you need to add them to your site so you can start using it. Open the _Layout.cshtml file located at Views/Shared/ and add the following code at the end of your head tag. Note that the polyfills and shims are declared before system.js and angular2. Additionally, in this case I added the router bundle to show you that you need to add additional bundles like Http and router (if you don’t need it, you can remove it).

<environment names="Development">
  <script src="~/lib/npmlibs/es6-shim/es6-shim.js"></script>
  <script src="~/lib/npmlibs/systemjs/system-polyfills.src.js"></script>
  <script src="~/lib/npmlibs/angular2/angular2-polyfills.js"></script>

  <script src="~/lib/npmlibs/systemjs/system.src.js"></script>
  <script src="~/lib/npmlibs/rxjs/Rx.js"></script>
  <script src="~/lib/npmlibs/angular2/angular2.js"></script>
  <script src="~/lib/npmlibs/angular2/router.js"></script>
</environment>

<environment names="Staging,Production">
  <script src="~/lib/npmlibs/es6-shim/es6-shim.min.js"></script>
  <script src="~/lib/npmlibs/systemjs/system-polyfills.js"></script>
  <script src="~/lib/npmlibs/angular2/angular2-polyfills.min.js"></script>

  <script src="~/lib/npmlibs/systemjs/system.src.js"></script>
  <script src="~/lib/npmlibs/rxjs/Rx.min.js"></script>
  <script src="~/lib/npmlibs/angular2/angular2.min.js"></script>
  <script src="~/lib/npmlibs/angular2/router.min.js"></script>
</environment>

Now, you have the dependencies in place for your ASP.NET Core and Angular 2 application, but if you plan to use TypeScript in your project you need to perform a few steps more. Create a tsconfig.json file in the root of your project to configure the compiler to include decorators and specify the use of system.js for module resolution.

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "module": "system",
    "moduleResolution": "node"
  },
  "exclude": [
    "node_modules",
    "wwwroot/lib"
  ]
}

If you try to compile the project now, you might find some TypeScript issues because Promise and other types are not defined. Add the es6-shim’s TypeScript definitions to your project. To do this, download the one from the DefinitelyTyped repository and add it to your project (you don’t need to serve this file, so you can have a ts folder with it in the root of the project).

Finally, let’s create the base structure for an Angular 2 application. We’ll create two TypeScript files inside a new folder named app under wwwroot. The first file will be the component, which will be a basic Hello World component. Create a file named app.component.ts inside the wwwroot/app folder and add the following code.

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: '<h1>My First Angular 2 App</h1>'
})
export class AppComponent { }

Now, create a file named boot.ts also inside the wwwroot/app folder and add the following code. This file is the one that you will load as start point of your app.

import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from './app.component'

bootstrap(AppComponent);

Open the view where you plan to add your Angular app, I will choose the Views/Home/Index.cshtml view. Add the angular component tag (e.g. <my-app></my-app>) to the html and add the following script section to the end of the file. This script will configure System.js (specifying to use js files whenever the extension it’s not defined) as well as initialize the Angular 2 app by importing the boot.js file located at the app folder.

@section Scripts {
    <script>
        System.config({
            packages: {
                'app': { defaultExtension: 'js' },
                'lib': { defaultExtension: 'js' },
            },
        });

        System.import('app/boot')
            .then(null, console.error.bind(console));
    </script>
}

You have the base structure for an ASP.NET Core and Angular 2 application. You can find the full code in my Angular2ASPNETCoreBaseApp repository. Now, you just need to start developing your awesome ideas.

Updated: I created a new post explaining how to configure routing to use Angular 2 Routing component.

Updated 2: I created a new post explaining how to configure Angular2’s Http service and ASP.NET to consume the MVC APIs.