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.
 
 
 
 

52 lines
1.7 KiB

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