Post

ASP.NET | Web APIs with Zipkin

Zipkin is a distributed tracing system that helps you monitor and troubleshoot microservices-based applications. This guide will walk you through the steps to integrate Zipkin with a C# Web API.

Prerequisites

Before you start, make sure you have the following prerequisites:

  1. .NET Core SDK installed on your system.
  2. A C# Web API project that you want to instrument with Zipkin.
  3. Zipkin server up and running (you can deploy Zipkin using Docker or as a standalone service).

Steps to Integrate Zipkin

Step 1: Install the Required Packages

You need to install the necessary packages to enable Zipkin integration in your C# Web API project. Open your project in the terminal or command prompt and use the following command to install the required NuGet packages:

1
2
3
dotnet add package OpenTracing
dotnet add package OpenTracing.Contrib.NetCore
dotnet add package Jaeger

Step 2: Configure Zipkin Tracing

In your C# Web API project, you’ll need to configure Zipkin tracing. Create a configuration class or use your existing configuration:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using Jaeger;
using Jaeger.Reporters;
using Jaeger.Samplers;
using Jaeger.Senders;
using OpenTracing;

public static class ZipkinConfig
{
    public static ITracer ConfigureTracer(string serviceName)
    {
        var reporter = new RemoteReporter.Builder()
            .WithSender(new UdpSender("your-zipkin-server-host", 9411, 0))
            .Build();

        var sampler = new ConstSampler(true);

        var tracer = new Tracer.Builder(serviceName)
            .WithReporter(reporter)
            .WithSampler(sampler)
            .Build();

        GlobalTracer.Register(tracer);
        return tracer;
    }
}

Step 3: Instrument Your Web API

In your Web API controllers or middleware, you can use the ITracer to start and finish spans, which represent different parts of your API request:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using Microsoft.AspNetCore.Mvc;
using OpenTracing;

[Route("api/[controller]")]
public class MyController : ControllerBase
{
    private readonly ITracer _tracer;

    public MyController(ITracer tracer)
    {
        _tracer = tracer;
    }

    [HttpGet]
    public ActionResult<string> Get()
    {
        using (var scope = _tracer.BuildSpan("MyController.Get").StartActive())
        {
            // Your API logic here
            return "Hello, World!";
        }
    }
}

Step 4: Start Zipkin and Observe Traces

Start your Zipkin server, and your C# Web API is now instrumented with Zipkin tracing. When you make requests to your API, you can use the Zipkin web UI to observe traces and troubleshoot issues in your microservices-based application.

What Next?

That’s it! You’ve successfully integrated Zipkin with your C# Web API to monitor and trace requests across your microservices.

This post is licensed under CC BY 4.0 by the author.