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.
 
 
 
 

53 lines
1.8 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.Request.Path == path && context.WebSockets.IsWebSocketRequest)
  16. {
  17. string subprotocol = null;
  18. if (context.Request.Headers.TryGetValue("Sec-WebSocket-Protocol", out var requestedSubProtocolValues))
  19. {
  20. // Order the protocols to also match "mqtt", "mqttv-3.1", "mqttv-3.11" etc.
  21. subprotocol = requestedSubProtocolValues
  22. .OrderByDescending(p => p.Length)
  23. .FirstOrDefault(p => p.ToLower().StartsWith("mqtt"));
  24. }
  25. var adapter = app.ApplicationServices.GetRequiredService<MqttWebSocketServerAdapter>();
  26. using (var webSocket = await context.WebSockets.AcceptWebSocketAsync(subprotocol))
  27. {
  28. await adapter.AcceptWebSocketAsync(webSocket);
  29. }
  30. }
  31. else
  32. {
  33. await next();
  34. }
  35. });
  36. return app;
  37. }
  38. public static IApplicationBuilder UseMqttServer(this IApplicationBuilder app, Action<IMqttServer> configure)
  39. {
  40. var server = app.ApplicationServices.GetRequiredService<IMqttServer>();
  41. configure(server);
  42. return app;
  43. }
  44. }
  45. }