MqttControllers 1.0.0

dotnet add package MqttControllers --version 1.0.0
                    
NuGet\Install-Package MqttControllers -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MqttControllers" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MqttControllers" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="MqttControllers" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add MqttControllers --version 1.0.0
                    
#r "nuget: MqttControllers, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package MqttControllers@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=MqttControllers&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=MqttControllers&version=1.0.0
                    
Install as a Cake Tool

MqttControllers

A lightweight library that brings ASP.NET Core-style controller routing to MQTT topics. Define message handlers using attributes — just like REST controllers — and let the framework dispatch incoming messages automatically.

Features

  • [MqttController] / [MqttRoute] / [MqttTopic] attributes mirroring ASP.NET's [ApiController] / [Route] / [HttpGet]
  • Route parameters extracted from topic segments (e.g. data/somedata)
  • PublishAsync() helper on the base class to send responses back through the broker
  • Auto-discovery of all MqttControllerBase subclasses in the entry assembly
  • Integrates with Kestrel via MQTTnet.AspNetCore

Requirements

Installation

Add the project reference or copy the library into your solution. The library itself depends on:

<PackageReference Include="MQTTnet" Version="5.1.0.1559" />
<PackageReference Include="MQTTnet.AspNetCore" Version="5.1.0.1559" />

Quick Start

1. Register the MQTT broker in Program.cs

var builder = WebApplication.CreateBuilder(args);

// Starts the MQTT broker on port 1883 (or any port you choose)
// and auto-discovers all MqttControllerBase subclasses.
builder.AddMqtt(1883);

// Optional: also serve HTTP endpoints on a separate port
builder.WebHost.ConfigureKestrel(k => k.Listen(IPAddress.Loopback, 5001));
builder.Services.AddControllers();

var app = builder.Build();

// Wires the MqttRouter into MQTTnet's message pipeline
app.UseMqtt();

app.UseRouting();
app.MapControllers();

await app.RunAsync();

2. Create an MQTT controller

using MqttAspCloud.MqttCore;
using MqttAspCloud.MqttCore.Attributes;

[MqttController]
[MqttRoute("data")]           // base prefix — optional
public class DataController : MqttControllerBase
{
    // Handles messages on: data/telemetry
    [MqttTopic("telemetry")]
    public Task OnTelemetry(string payload)
    {
        Console.WriteLine($"Telemetry received: {payload}");
        return Task.CompletedTask;
    }
}

3. Real-world example — AWS IoT provisioning simulation

This pattern is used in the MqttAspCloud project to simulate AWS IoT topic flows:

[MqttController]
[MqttRoute("$some")]
public class AuthMqttController : MqttControllerBase
{
    [MqttTopic("data/temperature")]
    public Task GetTemperature(string payload)
    {
        // Simulate some processing and return a response
        var response = new
        {
            temperature = 22.5,
            timestamp = DateTime.UtcNow
        };

        // Full topic resolved: $some/data/temperature
        return PublishAsync("$some/data/temperature",
                            JsonSerializer.Serialize(response));
    }
}

Attribute Reference

Attribute Target Description
[MqttController] Class Marks a class as an MQTT controller.
[MqttRoute("prefix")] Class Sets the topic prefix for all handlers in the class.
[MqttTopic("topic")] Method Defines the topic (or sub-topic) this method handles. Supports {param} placeholders, + single-level and # multi-level wildcards.

Topic resolution: {MqttRoute prefix}/{MqttTopic topic} → e.g. data/temperature

MqttControllerBase API

Member Description
MqttServer The injected MQTTnet.Server.MqttServer instance. Set automatically by UseMqtt().
PublishAsync(topic, payload) Publishes a UTF-8 string payload to the given topic via the broker.

Configuration (appsettings.json)

The Mqtt section is bound to MqttOptions and is optional:

{
  "Mqtt": {
    "Host": "localhost",
    "Port": 1883,
    "ClientId": "my-service",
    "Username": "",
    "Password": ""
  }
}

These values are available via IOptions<MqttOptions> injection in your controllers or services.

How It Works

  1. AddMqtt(port) — configures Kestrel to accept MQTT connections on the given port, registers all MqttControllerBase subclasses as singletons, and sets up the MqttRouter.
  2. UseMqtt() — hooks into MQTTnet's InterceptingPublishAsync event, extracts the topic and payload from every incoming message, and calls MqttRouter.DispatchAsync.
  3. MqttRouter — matches the incoming topic against every [MqttTopic] pattern, extracts {param} segments, and invokes the matching method with the resolved arguments.

Project Structure

MqttControllers/
├── Attributes/
│   ├── MqttControllerAttribute.cs   # [MqttController]
│   ├── MqttRouteAttribute.cs        # [MqttRoute("prefix")]
│   └── MqttTopicAttribute.cs        # [MqttTopic("topic")]
├── Extensions/
│   ├── MqttBuilderExtensions.cs     # AddMqtt() on WebApplicationBuilder
│   ├── MqttServerExtensions.cs      # UseMqtt() on WebApplication
│   └── MqttServiceExtensions.cs     # AddMqttControllers() on IServiceCollection
└── MqttCore/
    ├── MqttControllerBase.cs        # Base class for all MQTT controllers
    ├── MqttOptions.cs               # Options bound from "Mqtt" config section
    ├── MqttRouter.cs                # Topic pattern matching and dispatch
    └── MqttServerService.cs         # Low-level MQTTnet server wiring
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 100 4/27/2026