/fizzbuzz Using ASP.NET Core

What is ASP.NET Core?

From the official website,

ASP.NET is a popular web-development framework for building web apps on the .NET platform.

That's ASP.NET, ASP.NET Core is the cross-platform, open source version of ASP.NET.

ASP.NET Core is a fast and feature-rich web framework which leverages the open-source .NET Core (or .NET 5+) platform to deliver a rich development experience for building web applications of any scale. It is de facto web framework of choice in .NET land.

What is .NET/.NET Core?

Scott Hanselman comes to the rescue!

What will we be doing?

A gentle introduction to ASP.NET Core and C# by building an HTTP API which will allow us to calculate whether a given number n is "Fizz", "Buzz", or "FizzBuzz". Basic programing knowledge (enough knowledge to know what the modulo (%) operator does is sufficient).

The Requirements

  1. We first need to have .NET 5 on our system before we can proceed with writing the code. It can be downloaded from here, choose the platform of your choice and ensure that you're downloading the SDK and not just the runtime.
  2. A place to write your code. As the scope of this tutorial is artificially small, any functioning text editor will suffice. Popular options for more robust development .NET needs include Visual Studio, Visual Studio, and JetBrains Rider.

The Setup

  1. Ensure you have installed .NET 5 correctly by running dotnet --info on your terminal of choice. This will display information about the .NET installations on your system.
    1. If you're using Windows, use PowerShell.
  2. The command you had run, dotnet, is used to utilize the .NET CLI (Command Line Interface). It allows you to create new projects, build them, run tests, and much more.
  3. Create a new folder called "fizzbuzz" and go to it.
    1. mkdir fizzbuzz
    2. cd fizzbuzz
  4. Use the .NET CLI to create a new project in the current directory based on the "webapi" template.
    1. dotnet new webapi
    2. This command bootstraps a sample web API project in the specified folder. Ironically, the sample project is more complex than the project we are tackling.
  5. Run the sample project and inspect it.
    1. dotnet run
    2. dotnet run builds the project and runs it. dotnet build simply builds the project and so on. You can use dotnet -h to view the available options to the .NET CLI.
  6. As long as this tutorial is updated with any major changes to the "webapi" template or the .NET CLI, you should now have a running web application!
    1. You can visit https://localhost:5000/weatherforecast in your web browser to view the API in action.
    2. The sample web API project exposes a GET /weatherforecast endpoint which returns five random weather-related data entities.

Fizz the Buzz

From Wikipedia,

Players take turns to count incrementally, replacing any number divisible by three with the word "fizz", and any number divisible by five with the word "buzz".

Here's how a simple game of FizzBuzz would play out:

1

2

Fizz (3)

4

Buzz (5)

...

14

FizzBuzz (15)

Our goal is to implement an endpoint /fizzbuzz, not unlike /weatherforecast, which will accept a number and respond by running the rules of FizzBuzz on that number.

But how do we send a number as input?

We will be creating an HTTP GET endpoint and to pass the required information (the number), we will make use of the query parameters in the URL. In effect, our endpoint will perform as such:

  • /fizzbuzz?n=1 should return "1".
  • /fizzbuzz?n=3 should return "Fizz".
  • /fizzbuzz?n=5 should return "Buzz".
  • /fizzbuzz?n=15 should return "FizzBuzz".

Let us write some basic C# code for FizzBuzz:

string FizzBuzz(int n)
{
  if (n % 3 == 0)
  {
    return "Fizz";
  }
  if (n % 5 == 0)
  {
    return "Buzz";
  }
  if (n % 3 == 0 && n % 5 == 0)
  {
    return "FizzBuzz";
  }
  return n.ToString();
}

Now that we have written a function for performing FizzBuzz for a given number n, we are ready to expose this function to the web via a HTTP API.

FizzBuzzController


Clean Code

We will be writing a FizzBuzzController which will handle the concerns of the /fizzbuzz API endpoint. But first, let's do some cleaning:

  1. Remove the WeatherForecast.cs and the WeatherForecastController.cs files (the second one should be present in the Controllers folder).
  2. Let's skip HTTPS rerouting in development environment: Perform the below modification in Startup.cs:
app.UseHttpsRedirection();

to

if (!env.IsDevelopment())
{
  app.UseHttpsRedirection();
}

Now, let's write the FizzBuzzController:

  1. Create a new file FizzBuzzController.cs in the Controllers folder.
  2. Currently, we only need one namespace: Microsoft.AspNetCore.Mvc. Import it as using Microsoft.AspNetCore.Mvc.
  3. We need to keep our code within a namespace, let's call it FizzBuzz.Controllers and declare it by saying namespace FizzBuzz.Controllers.
  4. With the pre-requisites out of the way, let's finally write our controller by defining a new class, FizzBuzzController:

    [ApiController]
    [Route("[controller]")]
    public class FizzBuzzController : ControllerBase
    {
    // more code here
    }
    
    1. FizzBuzzController is our new class which inherits from ControllerBase (which allows us to use ASP.NET Core's built-in functionality for controllers.
    2. [ApiController] and [Route] are known as Attributes.
    3. ApiController allows us to leverage specific functionality intended for building web APIs (you'll know one such functionality soon).
    4. Route allows us to tell the ASP.NET Core framework to match the /fizzbuzz route with our FizzBuzzController.
  5. Let's write the method which will perform the FizzBuzz computation:

    [HttpGet]
    public string FizzBuzz([FromQuery] int n)
    {
    if (n % 3 == 0)
    {
     return "Fizz";
    }
    if (n % 5 == 0)
    {
     return "Buzz";
    }
    if (n % 3 == 0 && n % 5 == 0)
    {
     return "FizzBuzz";
    }
    return n.ToString();
    }
    
    1. What are [HttpGet] and [FromQuery]? You're right, they're attributes! HttpGet indicates to the framework that this method should be matched with an HTTP GET call to the endpoint. FromQuery instructs the framework to parse the parameter from the URL query parameters.
    2. [FromQuery] int n would match a query parameter with the name "n" and try to convert it to an int.
  6. Our code is now good to go, let's run and see how it goes!

    1. dotnet run (ensure that the previously started instance of the application was killed using Ctrl + C or similar signal).
    2. Visit http://localhost:5000/fizzbuzz?n=1 and see what happens! Now do it for /fizzbuzz?n=3 and /fizzbuzz?n=5 and see your code in action.
    3. Try visiting http://localhost:5000?n=notanumber. What do you expect will happen?
    4. We have earlier specified that we will obtain n from the query parameters after converting it to an int (integer).
    5. However, "notanumber" clearly cannot be converted to an integer. This means that we have bad input passed to our function.
    6. Thankfully, ApiController handles such cases automatically and returns an HTTP 400 Bad Request indicating that we sent an incorrect request.
  7. For reference, here's the full code for FizzBuzzController:

    namespace FizzBuzz.Controllers
    {
    using Microsoft.AspNetCore.Mvc;
    
    [ApiController]
    [Route("[controller]")]
    public class FizzBuzzController : ControllerBase
    {
     [HttpGet]
     public string FizzBuzz([FromQuery] int n)
     {
       if (n % 15 == 0)
       {
         return "FizzBuzz";
       }
       else if (n % 5 == 0)
       {
         return "Buzz";
       }
       else if (n % 3 == 0)
       {
         return "Fizz";
       }
       else
       {
         return n.ToString();
       }
     }
    }
    }
    

Wrapping Things Up

Congratulations! You've built your own FaaS (FizzBuzz as a Service) from the ground-up. Here's how you might want to continue your journey: