dotnet / dotnet/MQTTnet

Json serialized messages wont get published to the broker.

Open
#2,011 3 comments 0 reactions 0 assignees View on GitHub
question
Dominant language
C#
Stars
5.1k
Forks
1.2k
PR merge metrics
No merged PRs in 30d

Description

### Describe your question
I am building a .NET azure function app, The publish messages flow works fine so long as it is publishing hard coded strings, but as soon as I use a json serialized string the message won't get published for some reason. Wierdly enough when I try to step through the code via the Visual studio debugger, things start working. I can't identify what maybe the issue any help would be greatly appreciated.

### Here is some code for reproduction

```csharp

public class Function1
{
private readonly ILogger _logger;

public Function1(ILogger logger)
{
_logger = logger;
}

[Function("Function1")]
public async Task Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req)
{
const string HOST_URL = "xxx-xxx";
const int PORT = 8883;
const string TOPIC = "xxxxx";
string username = "xxxxx";
string randomName = Path.GetRandomFileName().Replace(".", string.Empty);

IEnumerable certList =
[
new("./certficate.pfx", "pass")
];

var factory = new MqttFactory();
var client = factory.CreateMqttClient();

var options = new MqttClientOptionsBuilder()
.WithTcpServer(HOST_URL, PORT)
.WithCredentials(username)
.WithClientId(randomName)
.WithCleanSession()
.WithTlsOptions(o => o.WithClientCertificates(certList))
.Build();

var m = JsonConvert.SerializeObject("Hello");
_logger.LogInformation(m); // This logs as expected

try
{
await client.ConnectAsync(options, req.HttpContext.RequestAborted);
var message = new MqttApplicationMessageBuilder()
.WithTopic(TOPIC)
.WithPayload(m) // This breaks
.Build();

await client.PublishAsync(message, req.HttpContext.RequestAborted);
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to handle MQTT operation.");
return new StatusCodeResult(StatusCodes.Status500InternalServerError);
}
finally
{
if (client.IsConnected)
{
await client.DisconnectAsync();
}
}

_logger.LogInformation("C# HTTP trigger function processed a request.");
return new OkObjectResult("Welcome to Azure Functions!");
}
}

```

### Which project is your question related to?

- Client

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.