Create A Dot Net Core REST Service With The Command Line Interface (CLI)

Webservice Oct 9, 2020

In this tutorial Create A Dot Net Core REST Service With The Command Line Interface (CLI) I guide you through the process of creating a RESTful Web service with dot net core and the dot net core command line interface (CLI).

This tutorial works on any supported operating system of dot net core like Windows, macOS or Linux.

Installing Dot Net Core and the CLI

First you have to download the Installer here. Select your operating system and follow the steps provided. Choose the latest version available.

You can verify the installation by opening up a terminal and type dotnetand hit ENTER. The terminal should output something like this:

patrick@MacBook-Pro ~ % dotnet

Usage: dotnet [options]
Usage: dotnet [path-to-application]

Options:
  -h|--help         Display help.
  --info            Display .NET Core information.
  --list-sdks       Display the installed SDKs.
  --list-runtimes   Display the installed runtimes.

Using the Command Line Interface

When typing a command starting with dot net in your terminal you are already using the command line interface. So, there is no graphical user interface (GUI). Just text and commands. This way of creating projects can speed up your workflow tremendously. There is no GUI which has to be maintained and updated. Find out about all the available commands from the dot net core CLI here.

Creating a new WebApi Project

The command line interface offers a new command with plenty of options. Find more details below or in the official documentation here.

dotnet new <TEMPLATE> [--dry-run] [--force] [-i|--install {PATH|NUGET_ID}]
    [-lang|--language {"C#"|"F#"|VB}] [-n|--name <OUTPUT_NAME>]
    [--nuget-source <SOURCE>] [-o|--output <OUTPUT_DIRECTORY>]
    [-u|--uninstall] [--update-apply] [--update-check] [Template options]

dotnet new <TEMPLATE> [-l|--list] [--type <TYPE>]

dotnet new -h|--help

For our Rest Service we are going to choose the webapi template. A more detailed information is linked here.

To create the most basic WebApi project you just have fire the new webapi command. The default name of the project is the parent folder.

patrick@MacBook-Pro webapi % dotnet new webapi

Eventually you should see somehting similar in your terminal.

Getting ready...
The template "ASP.NET Core Web API" was created successfully.

Processing post-creation actions...
Running 'dotnet restore' on /Users/patrick/dev/webapi/webapi.csproj...
  Wiederherzustellende Projekte werden ermittelt...
  "/Users/patrick/dev/webapi/webapi.csproj" wiederhergestellt (in 140 ms).

Restore succeeded.

That's it. You have successfully created a dot net core webapi project. Now let's run the app in the next step.

Running the Dot Net Core WebApi Project

Let's discover the content of the newly created project by running the ls (dir on Windows) command.

patrick@MacBook-Pro webapi % ls
Controllers			appsettings.Development.json
Program.cs			appsettings.json
Properties			obj
Startup.cs			webapi.csproj
WeatherForecast.cs

All REST Endpoints are grouped in the Controllers folder. With this template we do get a WeatherForecastController.cs generated in that Controllers folder. Keep in mind when Microsoft decides to update this template the content may change in the future.

patrick@MacBook-Pro webapi % cd Controllers 
patrick@MacBook-Pro Controllers % ls
WeatherForecastController.cs

That means if we run the applicatino we should GET something when calling the WeatherForecast endpoint.

Note: All Endpoints are usually without the Controller ending.

To start the application type the dotnet command in your terminal.

patrick@MacBook-Pro webapi % dotnet run
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: /Users/patrick/dev/webapi

Your web service is now up and running locally. Open a browser and navigate to http://localhost:5000/WeatherForecast. At this point you probably  will get redirected to the HTTPS URL. No worries, this is intended. You have three choices to continues.

  • Accept the untrusted certificate.
  • Create a new self signed certificate and trust it for development.
  • Deactive the HTTPS redirect in your Startup.cs.

When you choose the last point comment out this section of your code. Keep in mind that you NEVER want to deploy such a solution to a production environment.

namespace webapi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // app.UseHttpsRedirection(); <- Disable HTTPS Redirection

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

With both HTTP and HTTPS configurations you should see the following output when navigating to http://localhost:5000/WeatherForecast or https://localhost:5001/WeatherForecast.

[{"date":"2020-10-10T11:34:46.161044+02:00","temperatureC":54,"temperatureF":129,"summary":"Bracing"},{"date":"2020-10-11T11:34:46.161366+02:00","temperatureC":-2,"temperatureF":29,"summary":"Cool"},{"date":"2020-10-12T11:34:46.161372+02:00","temperatureC":53,"temperatureF":127,"summary":"Bracing"},{"date":"2020-10-13T11:34:46.161373+02:00","temperatureC":19,"temperatureF":66,"summary":"Cool"},{"date":"2020-10-14T11:34:46.161373+02:00","temperatureC":43,"temperatureF":109,"summary":"Mild"}]

The template GET endpoint looks like this the following code snippet.

[HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }

Try to play around with this, add new endpoints like Post, Put or Delete. Watch out to use the correct Attributes then like [HttpPost], [HttpPut] or [HttpDelete].

Watch the YouTube tutorial for an even more guided tour in under 5 minutes.

Have you any questions or tips for other programmers? Just put them in the comment section below. Happy hacking folks.

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.