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.