diff --git a/.github/workflows/ReleaseNotes.md b/.github/workflows/ReleaseNotes.md index 9e17c1aa..12c9dfeb 100644 --- a/.github/workflows/ReleaseNotes.md +++ b/.github/workflows/ReleaseNotes.md @@ -1,4 +1,5 @@ * [Client] Fixed _PlatformNotSupportedException_ when using Blazor (#1755, thanks to @Nickztar). +* [Client] Fixed _NullReferenceException_ when performing several actions when not connected (#1800, thanks to @ramonsmits). * [Server] Fixed _NullReferenceException_ in retained messages management (#1762, thanks to @logicaloud). * [Server] Exposed new option which allows disabling packet fragmentation (#1753). * [Server] Expired sessions will no longer be used when a client connects (#1756). diff --git a/Source/MQTTnet.Tests/Clients/MqttClient/MqttClient_Connection_Tests.cs b/Source/MQTTnet.Tests/Clients/MqttClient/MqttClient_Connection_Tests.cs index d38fc692..996f71eb 100644 --- a/Source/MQTTnet.Tests/Clients/MqttClient/MqttClient_Connection_Tests.cs +++ b/Source/MQTTnet.Tests/Clients/MqttClient/MqttClient_Connection_Tests.cs @@ -196,5 +196,27 @@ namespace MQTTnet.Tests.Clients.MqttClient Assert.AreEqual(response.UserProperties[0].Value, "Value"); } } + + [TestMethod] + public async Task Throw_Proper_Exception_When_Not_Connected() + { + try + { + var mqttFactory = new MqttFactory(); + using (var mqttClient = mqttFactory.CreateMqttClient()) + { + await mqttClient.SubscribeAsync("test", MqttQualityOfServiceLevel.AtLeastOnce); + } + } + catch (MqttCommunicationException exception) + { + if (exception.Message == "The client is not connected.") + { + return; + } + } + + Assert.Fail(); + } } } \ No newline at end of file diff --git a/Source/MQTTnet/Client/MqttClient.cs b/Source/MQTTnet/Client/MqttClient.cs index 2b851ea6..938348e8 100644 --- a/Source/MQTTnet/Client/MqttClient.cs +++ b/Source/MQTTnet/Client/MqttClient.cs @@ -321,14 +321,14 @@ namespace MQTTnet.Client MqttTopicValidator.ThrowIfInvalidSubscribe(topicFilter.Topic); } + ThrowIfDisposed(); + ThrowIfNotConnected(); + if (Options.ValidateFeatures) { MqttClientSubscribeOptionsValidator.ThrowIfNotSupported(options, _adapter.PacketFormatterAdapter.ProtocolVersion); } - ThrowIfDisposed(); - ThrowIfNotConnected(); - var subscribePacket = MqttPacketFactories.Subscribe.Create(options); subscribePacket.PacketIdentifier = _packetIdentifierProvider.GetNextPacketIdentifier();