.NET Tutorial - Hello World Microservice

Create your service

Create an app

In your command prompt, run the following commands:

In your terminal, run the following commands:

Command prompt
dotnet new webapi -o myMicroservice --no-https
cd myMicroservice

The dotnet command creates a new application of type webapi (that's a REST API endpoint).

  • The -o parameter creates a directory named myMicroservice where your app is stored.
  • The --no-https flag creates an app that will run without an HTTPS certificate, to keep things simple for deployment.

The cd myMicroService command puts you into the newly created app directory.

The generated code

Several files were created in the myNewMicroService directory, to give you a simple service that is ready to run.

  • myMicroservice.csproj defines what libraries the project references etc.
  • Startup.cs contains all the settings and configuration that are loaded when the app starts.
  • Controllers/WeatherForecastController.cs has code for a simple API that returns the weather forecast for the next five days.
WeatherForecastController.cs (shortened for clarity)
public class WeatherForecastController : ControllerBase
    private static readonly string[] Summaries = new[]
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
        _logger = logger;

    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)]