Monday 10 August 2020

Create a C# Core REST API

I started my career working with Visual Basic 6.0... soon after I Switched to win-forms in visual studio, then to web-forms, then to UWP's and XAMARIN forms with each transition relying less frequently on the WYSIWYG to such a point were I just stopped using it, in the same way that a drug addict weens him or herself (wouldn't want to be accused of sexism) off of crack once they hit rock bottom, my rock bottom was SharePoint... 

Anyway enough of my autobiography "Sucking SharePoint for money", it's time to start a second volume; currently my working title is "Stealing candy from babies, making a living the merican way".

So lets get started, in this post we are going to set up a simple out of the box rest API, open up your windows terminal 

one can create a dotnet project using any terminal, i just prefer the "windows terminal" because it brings me back to DOS and I'm getting nostalgic in my final years...

for a bonus type in "dotnet new" to see all the initial templates available to you.

once you hit enter it should take about 10 seconds and voila you have your first API.

keep in mind that we manually created our file folder, we could have done something along the lines of "donet new webapi -n <project name>"

now to take a look at what you have created, ether type in the "dir" command to view a listing of the directory in your terminal or "explorer ." to open it up in your windows explorer.

and the explorer view

now that is probably not all that exciting, however you can see that it is there, next lets open this sucker in VS Code; type in "code ."

now that our project is open VS Code

notice the dialog in the bottom right, make sure to click yes on it; you may be wondering what happens if you don't, well the answer is simple... henchmen from the Microsoft corporation come to your house and buy you out.

with our template created, lets test it to see what happens; in your terminal of choice type in dotnet run (assuming that you are in your project folder).

now your api is up and running locally on your machine, you can navigate to https://localhost:5001/weatherforecast on your local machine and you should see something like the following.

It's just some simple JSON output coming from our weatherforecast controller, and if you are wondering WTF is that, well lets head back to our project in VS code and take a look.


in the left hand column you can see our WeatherForcastController file, you can think of this as our webpage, but instead of returning HTML that our browser renders, it contains functions that return data, generally as JSON but way back when I first started with SOAP service they were returning XML, why the change you may ask, well because in the early 2000's the internet hated Microsoft and apparently JSON was far superior due to the fact that it was far less verbose, meaning that it was shorter and you have to transfer less data, how much less you may ask? well it depends on the payload, but compared to an audio file the difference was competently insignificant, that being said it was also a time when mobile data was very expensive so it did serve a purpose.

I'm not shitting on JSON, I think it is just fine, but by no means is it the game changer that it has been made out to be. in short JSON is shorter than XML, XML is more human readable, 99% of the time it wouldn't make a difference which you use, however 99.9% of the time you will be made fun of for using XML, thus save yourself ridicule and use JSON, but just be aware that in a legacy system if you hear the words SOAP Service it will most likely be passing data around as XML.

But i degress, lets take a look at our Controller

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace pav.Controllers {
  public class WeatherForecastController : ControllerBase {
    private static readonly string[] Summaries = new[] {

    private readonly ILogger<WeatherForecastController_logger;

    public WeatherForecastController(ILogger<WeatherForecastControllerlogger) {
      _logger = logger;

    public IEnumerable<WeatherForecastGet() {
      var rng = new Random();

      return Enumerable.Range(15).Select(index => new WeatherForecast {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-2055),
        Summary = Summaries[rng.Next(Summaries.Length)]

notice the two attributes on our class [ApiController] and [Route("[controller]")] the first marks our class as an API Controller and then through the magic of Reflection our API Application "knows" that this class contains api endpoints. the second is the route, this specifies the url path after our domain address, so if we changed it from 

namespace pav.Controllers {
  public class WeatherForecastController : ControllerBase {
   //removed for brevity


namespace pav.Controllers {
  public class WeatherForecastController : ControllerBase {
   //removed for brevity

and we restarted our api but clicking ctrl+C in our terminal and executing dotnet run again we now would have to modify our url accordingly.


if we update our URL to https://localhost:5001/api/v1/weatherforecast

we are up and running once again, now the reason why we appended this api route with a version number is because often times your api will be supporting multiple versions of consumers. so for example you may have a web application that uses version 1 then you may add a mobile app that uses a newer version say version 2 that needs some new endpoints, that do the same thing but slightly differently. anyway save your future self some headaches and version your API right from the get go.

It also would make sense for you to adjust your folder structure accordingly, so just add a v1 folder to your controllers and move your weatherforecast controller into it, notice that Code give you this horizontal display when you have just one child folder

Should you add a second V2 folder it will look more familiar

now if you rerun your application everything will work as before, keep in mind that your folder structure and your namespaces are usually aligned out of convention, by no means do they need to be.

anyway I think that is enough for today.