Friday, 28 April, 2017 UTC


Summary

".NET Core 1.0 is here!" he shouts. "After all this waiting, it has finally been released!". He rushes to his development machine, hits up the .NET Core Website and discovers that it's already at version 1.1.0. "Wait, version 1.0 was released June last year!?"
Okay, so I'm a little late to the party. About 6 months ago I got an awesome new job and shifted gears from general dogs-body - er - I mean "full stack" development to focus more on the front-end. I'm living in a JavaScript world now, there's enough Nodes, Gulps, Angulars, and Vues to keep me busy for a long time. That said, I have been very aware of this beast named .NET Core, and have been excited to see the direction Microsoft are taking it. Though I haven't ever taken a real look at it, until now.
So I thought I'd reboot this blog with a post on how to get quickly get up and running using .NET Core, from scratch.
In this post we are going to achieve the following:
  • Install .NET Core
  • Create an empty project
  • Perform the wiring required to get a RESTful API set up
  • Run the App
This wont be a comprehensive tutorial on ASP.NET MVC6 or building APIs using it, I just want to focus on getting something working using .NET Core for now. This is a bit of a long one, so let's get started.
What is .NET Core?
For those that don't know, let's start with the basics, what is .NET Core?
.NET Core is the modular and high performance implementation of .NET for creating web applications and services that run on Windows, Linux and Mac. It is open source and it can share the same code with .NET Framework and Xamarin apps.
There it is straight from the horses mouth, it's a free, open-source implementation of the .NET Runtime, the feature that gets me most excited is the that...
It's Multiplatform now!
That's right, you're no longer tied to Windows Servers and Windows Development machines if you want to create and run apps using .NET. .NET Core 1.0 runs on Windows, Mac, and Linux.
Microsoft have also released a neat little editor called Visual Studio Code. This has already been my default editor for some time now, as its multi-platform it's a great tool to use for development of .NET Apps on OSX and Linux.
Installation
Installing .NET Core is pretty simple, but it does differ depending on what OS you are using, rather than reinvent the wheel here I will just direct you to Microsofts handy site with instructions on how to get started no matter what OS you are using: https://www.microsoft.com/net/core
For this guide I will be building an app using the command line tools and Visual Studio Code. So we can see under the hood how this all works, which is handy when working in Mac and Linux, if you're not interested in that just grab Visual Studio 2017 and that will do most of the heavy lifting for you.
Command Line Tools!
.NET Core has a neat CLI tool that you can use to create, build, run, and package apps. If you've ever done anything with node then you will feel right at home here. The concepts are very similar.
To check if the CLI is installed on your system simply type dotnet into the terminal/command line/powershell and it will output the current version of .NET you have installed, along with some quick documentation on how to get started using it.
If you enter dotnet --help you will see a handy list of all the commands available to you with an explanation on what they do. Armed with this tool, let's create a super simple RESTful API.
Setting up the Project
Create a new directory and CD into it, we're going to use the CLI to create a new application.
To do this we enter dotnet new. If you're doing this for the first time, dotnet will need to go off and do some configuration, this only takes a couple of minutes so let it do it's thing.
Once done, you will notice it doesn't create the application, but instead give you a list of project types you can create.
Templates                 Short Name      Language      Tags
----------------------------------------------------------------------
Console Application       console         [C#], F#      Common/Console
Class library             classlib        [C#], F#      Common/Library
Unit Test Project         mstest          [C#], F#      Test/MSTest
xUnit Test Project        xunit           [C#], F#      Test/xUnit
ASP.NET Core Empty        web             [C#]          Web/Empty
ASP.NET Core Web App      mvc             [C#], F#      Web/MVC
ASP.NET Core Web API      webapi          [C#]          Web/WebAPI
Solution File             sln                           Solution
Anyone already familiar with creating .NET apps with Visual Studio will be comfortable with these options, these are a list of general project types that you can use as a jumpstart for your own work. Normally you'd want to pick WebApi in our case, but I want to know how to wire this stuff up myself. So instead I'm going to create an Empty project by entering dotnet new web.
Listing out the files with ls you will see the CLI has created a few files for us, open these up in your editor of choice now.
Startup.cs - It's important.
Let's open up the Startup.cs file, this is the file we will use to wire up our application, add configuration, set up middleware, etc.
In the Configure block you should see the following code:
app.Run(async (context) =>
{
  await context.Response.WriteAsync("Hello World!");
});
What this is essentially doing is logging out "Hello World!" onto the page when a request is received. So we already have something we can run and see some output. Cool.
Running the App
We also use the CLI to run the app, to do this we enter dotnet run into the terminal. Do that now, I'll wait.
Did it work? No? hm... Looks like we have a whole lot of errors. Turns out all of our projects dependencies are missing. We need to restore them. This is the same concept as grabbing packages from Nuget or NPM in the Node world.
There's no setup required for this right now, we can just run dotnet restore once and it will download all of the required project dependencies. Once that's done try dotnet run again. You should see output similar to the following:
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
The application is running on http://localhost:5000, so go there in your browser. Some request info will pop up on the command line, and you should see "Hello World!" output to the browser.
If you like, you can change this message by changing the string inside of the code above. I'm not going to do that though, I want a RESTful API and I want it now.
Adding MVC6
So it turns out that WebAPI2 is gone, MVC6 is the king now. All of the functionality we know and love from Web API has now been rolled into MVC6, this is a great change. It makes life a little simpler, and I like simple.
So how do we tell our app we want to use MVC6? Pretty easily, actually. We need to add some statements in a couple of areas inside Startup.cs.
The first thing we need to do is add a line in the ConfigureServices method that tells our app to bring in all of the Mvc services.
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
}
ConfigureServices let's us do all sorts of cool stuff, the thing I'm most happy about is how we can use it for Dependency Injection right here in ASP.NET without needing any third party tools, but that is out of the scope of this post.
Next, we will delete all of the app.Run() code, as we no longer need it, and instead replace it with the following:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    //... Logger Factory and DevelopmentExceptionPage code here

    app.UseMvc();
}
This is telling our app to use the Mvc middleware to handle requests. If you're using Visual Studio, it's likely you're getting some errors here, because the compiler does not understand what Mvc is currently. If you're not using Visual Studio, the app will explode when you try and run it.
This brings us to another major change to .NET Core, modularity. By default a .NET Core project will have very little dependencies bought into it, its up to you to pick and chose the bits you need. In our case we need to add MVC6 as project dependency and install it. Let's do that now.
Managing Project Dependencies
When I first had a quick glance into this, dependencies were managed in a project.json file, it seems somewhere down the line this changed, and they are now managed in the .csproj file. I'm not sure why this change was made, but let's just roll with it for now.
Opening up the <your app name>.csproj file we will see a few default settings that have already been included. Such as the Target Framework, Static Files folder, and a reference to the Microsoft.AspNetCore package. This is a dependency that has already been added to the project when we ran dotnet new, we installed it when we first ran dotnet restore.
Lets add a new line underneath this one, to include MVC as a dependency.
<ItemGroup>
  <PackageReference Include="Microsoft.AspNetCore" Version="1.1.1" />
  <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.2" />
</ItemGroup>
We will now need to close our running app in the terminal by hitting ctrl+c and then install our new dependencies with dotnet restore and we can then re-run our app with dotnet run.
Now lets go to localhost:5000 and... get a 404 error. That's fine, it's just because we don't have any controllers telling our app what it needs to do.
Adding a Controller
First, create a new folder at the root of our project called Controllers, then create a C# file in that folder called PeopleController.cs. Open that up in your editor and let's write the code we need.
We're going to need the following using statements for this controller:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
Next we'll set up a simple class that inherits from Controller. Those of you that may be used to WebAPI of old might remember we used to inherit from ApiController. Not anymore, the standard Controller base class has us covered now, it's all we need. Also let's be good little coders and wrap it in a namespace.
namespace DotNetCoreAdventures.Controllers
{
    public class PeopleController : Controller
    {
    }
}
In the PeopleController we can now create a method called Get, which returns a list of strings. Making our full PeopleController.cs file look like this:
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace DotNetCoreAdventures.Controllers
{
    public class PeopleController : Controller
    {
        public List<string> Get()
        {
            var people = new List<string>
            {
                "Sona Filkins",
                "Glen Dorey",
                "Deborah Gadson"
            };

            return people;
        }
    }
}
Simple enough, we're setting up a list of strings, with a bunch of names I got from an online generator, and returning them when called. Lets run the app again with dotnet run in the command line and see our API in action!
Oh...
Another 404.
Adding a Route
So, we're getting another 404 error here because while we have a controller, we don't have any routes specified. Luckily this is incredibly simple to do. You simply decorate the Get method with the Route attribute, passing it the route you would like to use, like this:
        public List<string> Get()
        {
            [Route("/api/people")]
            var people = new List<string>
            {
                "Sona Filkins",
                "Glen Dorey",
                "Deborah Gadson"
            };

            return people;
        }
This tells ASP.NET that to access this action you need to hit the /api/people URI in the browser.
You can also set these routes in the app.UseMvc() method in Startup.cs, which works almost identically to the WebApiConfig.cs files of old. But I won't be going into that here. There are plenty of examples of that online if you're interested.
Alright, lets start up our app again with dotnet run, navigate to localhost:5000/api/people and finally we have some data being returned. You should be getting back an array of names.
[
    "Sona Filkins",
    "Glen Dorey",
    "Deborah Gadson"
]
Cool!
As you can see, there isn't a whole lot of work needed up front to get a simple API set up, it's even easier if you just let dotnet new create a base API for you, but wheres the fun in that?
All in all I'm enjoying the direction that .NET Core is taking, and very much look forward to seeing how it evolves in the future.
This is probably a good place to stop for now, but in the future I want to cover dependency injection, publishing to Linux and using Nginx as a reverse proxy, and my favorite, running .NET Core apps in a Docker Container.
Until next time!