You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

58 lines
1.9 KiB

  1. using System;
  2. using Microsoft.AspNetCore.Builder;
  3. using Microsoft.Extensions.DependencyInjection;
  4. using System.Linq;
  5. using MQTTnet.Server;
  6. using System.Collections.Generic;
  7. namespace MQTTnet.AspNetCore
  8. {
  9. public static class ApplicationBuilderExtensions
  10. {
  11. public static IApplicationBuilder UseMqttEndpoint(this IApplicationBuilder app, string path = "/mqtt")
  12. {
  13. app.UseWebSockets();
  14. app.Use(async (context, next) =>
  15. {
  16. if (!context.WebSockets.IsWebSocketRequest || context.Request.Path != path)
  17. {
  18. await next();
  19. return;
  20. }
  21. string subProtocol = null;
  22. if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues))
  23. {
  24. subProtocol = SelectSubProtocol(requestedSubProtocolValues);
  25. }
  26. var adapter = app.ApplicationServices.GetRequiredService<MqttWebSocketServerAdapter>();
  27. using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subProtocol))
  28. {
  29. await adapter.RunWebSocketConnectionAsync(webSocket, context);
  30. }
  31. });
  32. return app;
  33. }
  34. public static string SelectSubProtocol(IList<string> requestedSubProtocolValues)
  35. {
  36. // Order the protocols to also match "mqtt", "mqttv-3.1", "mqttv-3.11" etc.
  37. return requestedSubProtocolValues
  38. .OrderByDescending(p => p.Length)
  39. .FirstOrDefault(p => p.ToLower().StartsWith("mqtt"));
  40. }
  41. public static IApplicationBuilder UseMqttServer(this IApplicationBuilder app, Action<IMqttServer> configure)
  42. {
  43. var server = app.ApplicationServices.GetRequiredService<IMqttServer>();
  44. configure(server);
  45. return app;
  46. }
  47. }
  48. }