Files
MQTTnet/Source/MQTTnet/Protocol/MqttTopicValidator.cs
T
ChristianandHansM 795139d78f Add feature validations (#1527)
* Add feature validation.

* Update ReleaseNotes.md

* Add validators or subscribe and unsubscribe.

* Add feature validation for disconnect.

* Fix build errors.

* Fix build errors

Co-authored-by: HansM <HansM2013@gmx.de>
2022-12-23 16:56:11 +01:00

60 lines
1.9 KiB
C#

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using MQTTnet.Exceptions;
namespace MQTTnet.Protocol
{
public static class MqttTopicValidator
{
public static void ThrowIfInvalid(MqttApplicationMessage applicationMessage)
{
if (applicationMessage == null)
{
throw new ArgumentNullException(nameof(applicationMessage));
}
if (applicationMessage.TopicAlias == 0)
{
ThrowIfInvalid(applicationMessage.Topic);
}
}
public static void ThrowIfInvalid(string topic)
{
if (string.IsNullOrEmpty(topic))
{
throw new MqttProtocolViolationException("Topic should not be empty.");
}
foreach (var @char in topic)
{
if (@char == '+')
{
throw new MqttProtocolViolationException("The character '+' is not allowed in topics.");
}
if (@char == '#')
{
throw new MqttProtocolViolationException("The character '#' is not allowed in topics.");
}
}
}
public static void ThrowIfInvalidSubscribe(string topic)
{
if (string.IsNullOrEmpty(topic))
{
throw new MqttProtocolViolationException("Topic should not be empty.");
}
var indexOfHash = topic.IndexOf("#", StringComparison.Ordinal);
if (indexOfHash != -1 && indexOfHash != topic.Length - 1)
{
throw new MqttProtocolViolationException("The character '#' is only allowed as last character");
}
}
}
}