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
- 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.
- 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
- 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. - If you’re using Windows, use PowerShell.
- 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. - Create a new folder called “fizzbuzz” and go to it.
mkdir fizzbuzz
cd fizzbuzz
- Use the .NET CLI to create a new project in the current directory based on the “webapi” template.
dotnet new webapi
- 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.
- Run the sample project and inspect it.
dotnet run
dotnet run
builds the project and runs it.dotnet build
simply builds the project and so on. You can usedotnet -h
to view the available options to the .NET CLI.- 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!
- You can visit
https://localhost:5000/weatherforecast
in your web browser to view the API in action. - The sample web API project exposes a GET /weatherforecast endpoint which returns five random weather-related data entities.
Fizz the Buzz
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
app.UseHttpsRedirection();
to
if (!env.IsDevelopment())
{
app.UseHttpsRedirection();
}
Now, let’s write the FizzBuzzController
:
- Create a new file
FizzBuzzController.cs
in theControllers
folder. - Currently, we only need one namespace:
Microsoft.AspNetCore.Mvc
. Import it asusing Microsoft.AspNetCore.Mvc
. - We need to keep our code within a namespace, let’s call it
FizzBuzz.Controllers
and declare it by sayingnamespace FizzBuzz.Controllers
. - 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
}
-
FizzBuzzController
is our new class which inherits fromControllerBase
(which allows us to use ASP.NET Core’s built-in functionality for controllers. -
[ApiController]
and[Route]
are known as Attributes. -
ApiController
allows us to leverage specific functionality intended for building web APIs (you’ll know one such functionality soon). -
Route
allows us to tell the ASP.NET Core framework to match the/fizzbuzz
route with ourFizzBuzzController
. -
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();
}
-
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. -
[FromQuery] int n
would match a query parameter with the name “n” and try to convert it to anint
. -
Our code is now good to go, let’s run and see how it goes!
-
dotnet run
(ensure that the previously started instance of the application was killed using Ctrl + C or similar signal). -
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. -
Try visiting
http://localhost:5000?n=notanumber
. What do you expect will happen? -
We have earlier specified that we will obtain
n
from the query parameters after converting it to anint
(integer). -
However, “notanumber” clearly cannot be converted to an integer. This means that we have bad input passed to our function.
-
Thankfully,
ApiController
handles such cases automatically and returns an HTTP 400 Bad Request indicating that we sent an incorrect request. -
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:
- Create an API which performs CRUD operations
- Learn more about designing HTTP APIs
- Fix bugs in your FaaS.
- Provide suggestions to me to write more (and hopefully better) content!