diff --git a/Source/MQTTnet.AspnetCore/ApplicationBuilderExtensions.cs b/Source/MQTTnet.AspnetCore/ApplicationBuilderExtensions.cs index 22b9e937..2125c7df 100644 --- a/Source/MQTTnet.AspnetCore/ApplicationBuilderExtensions.cs +++ b/Source/MQTTnet.AspnetCore/ApplicationBuilderExtensions.cs @@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using System.Linq; using MQTTnet.Server; +using System.Collections.Generic; namespace MQTTnet.AspNetCore { @@ -23,10 +24,7 @@ namespace MQTTnet.AspNetCore if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues)) { - // Order the protocols to also match "mqtt", "mqttv-3.1", "mqttv-3.11" etc. - subProtocol = requestedSubProtocolValues - .OrderByDescending(p => p.Length) - .FirstOrDefault(p => p.ToLower().StartsWith("mqtt")); + subProtocol = SelectSubProtocol(requestedSubProtocolValues); } var adapter = app.ApplicationServices.GetRequiredService(); @@ -40,6 +38,14 @@ namespace MQTTnet.AspNetCore return app; } + public static string SelectSubProtocol(IList requestedSubProtocolValues) + { + // Order the protocols to also match "mqtt", "mqttv-3.1", "mqttv-3.11" etc. + return requestedSubProtocolValues + .OrderByDescending(p => p.Length) + .FirstOrDefault(p => p.ToLower().StartsWith("mqtt")); + } + public static IApplicationBuilder UseMqttServer(this IApplicationBuilder app, Action configure) { var server = app.ApplicationServices.GetRequiredService(); diff --git a/Tests/MQTTnet.TestApp.AspNetCore2/Startup.cs b/Tests/MQTTnet.TestApp.AspNetCore2/Startup.cs index f52040a0..db352f3c 100644 --- a/Tests/MQTTnet.TestApp.AspNetCore2/Startup.cs +++ b/Tests/MQTTnet.TestApp.AspNetCore2/Startup.cs @@ -22,13 +22,18 @@ namespace MQTTnet.TestApp.AspNetCore2 .Build(); services .AddHostedMqttServer(mqttServerOptions) - .AddMqttConnectionHandler(); + .AddMqttConnectionHandler() + .AddConnections(); } // In class _Startup_ of the ASP.NET Core 2.0 project. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { - app.UseMqttEndpoint(); + app.UseConnections(c => c.MapConnectionHandler("/mqtt", options => { + options.WebSockets.SubProtocolSelector = MQTTnet.AspNetCore.ApplicationBuilderExtensions.SelectSubProtocol; + })); + + //app.UseMqttEndpoint(); app.UseMqttServer(server => { server.Started += async (sender, args) =>