.NET Tutorial - Your First Microservice

Create your service

In your command prompt, run the following command to create your app:

In your terminal, run the following command to create your app:

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

Then, navigate to the new directory created by the previous command:

Command prompt
cd myMicroservice

What do these commands mean?

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)
[ApiController]
[Route("[controller]")]
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;
    }

    [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();
    }
}
Continue